Home >Backend Development >PHP Problem >Use php to verify whether a string is a number
It is very easy to use regular expressions to verify whether a string is a number in php
. The most important thing is how to write regular expressions and master regular expressions. As for how to write expressions, here we use regular expressions to list ways to judge numbers.
The first method:
Use the function is_numeric() to verify
bool is_numeric ( mixed $var )
$var: Variable to be detected
Return value: TRUE if the specified variable is a number or numeric string, otherwise it returns FALSE, pay attention to floating point Type returns a null value, which is FALSE.
if(is_numeric($str)) echo('是数字'); else echo('不是数字');
Second method:
Use regular expression verification
<?php if($str) { if(eregi("^[0-9]+$",$str)) { $str=(int)$str; }else{ echo "获取到的数据不是有效的数字类型,操作将停止!"; exit(); } }else{ echo "需要验证的数据为空,操作停止!"; exit(); } ?>
Recommended: "php video tutorial" "php tutorial"
The above is the detailed content of Use php to verify whether a string is a number. For more information, please follow other related articles on the PHP Chinese website!