Scott
Scott

Reputation: 3485

Check if variable has a number php

I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:

"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true

There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.

Upvotes: 19

Views: 27808

Answers (5)

Abhishek Madhani
Abhishek Madhani

Reputation: 1175

Holding on to spirit of @Martin, I found a another function that works in similar fashion.

(strpbrk($var, '0123456789')

e.g. test case

<?php

function a($var) {
    return (strcspn($var, '0123456789') != strlen($var));
}

function b($var) {
    return (strpbrk($var, '0123456789'));
}

$var = array("abc", "!./#()", "!./#()abc", "123", "abc123", "!./#()123", "abc !./#() 123");

foreach ($var as $v) {
    echo $v . ' = ' . b($v) .'<hr />';
}

?>

Upvotes: 8

Tomalak
Tomalak

Reputation: 338208

$result = preg_match("/\\d/", $yourString) > 0;

Upvotes: 12

Peter Perh&#225;č
Peter Perh&#225;č

Reputation: 20782

This should help you:

$numberOfNumbersFound = preg_match("/[0-9]+/", $yourString);

You could get more out of the preg_match function, so have a look at its manual

Upvotes: 4

farzad
farzad

Reputation: 8855

you can use this pattern to test your string using regular expressions:

$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;

Upvotes: -2

Martin Geisler
Martin Geisler

Reputation: 73768

You can use the strcspn function:

if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
  echo "true";
else
  echo "false";

strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.

There is no need to invoke the regular expression engine for this.

Upvotes: 69

Related Questions