如何使用PHP检测字符串中的数字

Pro*_*zip 4 php numbers range detect

这是test.php文件:

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

?>
Run Code Online (Sandbox Code Playgroud)

它按字符分割字符串,并检查字符是否为数字。

问题:其输出始终为 “此变量包括数字”。请帮助我找到原因。提示:当我更改为时range(0,9),range(1,9)它可以正常工作(但无法检测到0)。

One*_*One 12

你可以只使用正则表达式:

$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';
Run Code Online (Sandbox Code Playgroud)


hek*_*mgl 9

用途preg_match():

if (preg_match('~[0-9]+~', $string)) {
    echo 'string with numbers';
}
Run Code Online (Sandbox Code Playgroud)

尽管您不应该使用它,因为它比preg_match()我将解释为什么原始代码无法运行的速度慢得多:

字符串中的非数字字符与数字(in_array()内部进行比较)将被视为0数字。检查以下示例:

var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)
Run Code Online (Sandbox Code Playgroud)

正确的方法是在is_numeric()这里使用:

$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(is_numeric($string[$i]))  {
       $keyword = 'includes';
       break;
    }
}
Run Code Online (Sandbox Code Playgroud)

或使用数字的字符串表示形式:

$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;
    }
}
Run Code Online (Sandbox Code Playgroud)