这是 test.php 文件:
$string = 'A string with no numbers';
for ($i = 0; $i <= strlen($string)-1; $i++) {
$char = $string[$i];
$message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}
// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));
// function
function codeStyle($string) {
return '<span style="background-color: #eee; font-weight: bold;">' . $string . '</span>';
}
它逐字符拆分字符串并检查字符是否为数字。
问题:它的输出总是“这个变量包含 number(s)”。请帮我找出原因。
提示:当我将 range(0,9)
更改为 range(1,9)
时,它可以正常工作(但无法检测到 0)。
最佳答案
使用preg_match()
:
if (preg_match('~[0-9]+~', $string)) {
echo 'string with numbers';
}
尽管您不应该使用它,因为它比 preg_match()
慢得多,但我将解释为什么您的原始代码不起作用:
字符串中的非数字字符与数字相比时(in_array()
在内部执行此操作)将被评估为 0
什么是数字。检查这个例子:
var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)
正确的做法是在此处使用 is_numeric()
:
$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
if(is_numeric($string[$i])) {
$keyword = 'includes';
break;
}
}
或者使用数字的字符串表示:
$keyword = 'doesn\'t include';
// the numbers as stings
$numbers = array('0', '1', '2', /* ..., */ '9');
for ($i = 0; $i <= strlen($string)-1; $i++) {
if(in_array($string[$i], $numbers)){
$keyword = 'includes';
break;
}
}
关于php - 检测字符串是否包含任何数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18683444/