Check if variable has a number php

走远了吗. 提交于 2019-12-02 15:39:05

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.

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

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 />';
}

?>

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

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

$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!