检查变量是否有数字 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/901708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if variable has a number php
提问by Scott
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.
如果您想知道所有数字但不是只有一个数字,则有一些简单的方法可以做到这一点。谢谢你的帮助。
回答by Martin Geisler
You can use the strcspnfunction:
您可以使用该strcspn功能:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspnreturns 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.
strcspn返回不包含任何整数的部分的长度。我们将它与字符串长度进行比较,如果它们不同,那么一定是一个整数。
There is no need to invoke the regular expression engine for this.
无需为此调用正则表达式引擎。
回答by Tomalak
$result = preg_match("/\d/", $yourString) > 0;
回答by Abhishek Madhani
Holding on to spirit of @Martin, I found a another function that works in similar fashion.
秉承@Martin 的精神,我发现了另一个以类似方式工作的功能。
(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 />';
}
?>
回答by Peter Perhá?
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
你可以从 preg_match 函数中得到更多,所以看看它的手册
回答by farzad
you can use this pattern to test your string using regular expressions:
您可以使用此模式使用正则表达式测试您的字符串:
$isNumeric = preg_match("/\S*\d+\S*/", $string) ? true : false;

