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

时间:2013-09-08 12:00:59

标签: 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>';
}

?>

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

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

5 个答案:

答案 0 :(得分:6)

使用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;
    }
}

答案 1 :(得分:2)

您可以使用regexp

$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';

答案 2 :(得分:2)

这是因为PHP松散类型比较,你将字符串与整数进行比较,因此PHP内部会将此字符串转换为整数,并且字符串中的所有字符都将被转换为0。

修复代码的第一步是创建一个字符串数组而不是整数:

$numbers = array_map(function($n){ return (string)$n; }, range(0,9));
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char,$numbers)?'includes' : 'doesn\'t include';
}

这将修复您的情况,但不会按预期工作,因为$message_keyword会在每个循环上被覆盖,因此只会收到最后一个字符的消息。如果您的目标只是检查字符串是否包含数字,您可以在遇到第一个数字后停止检查:

$message_keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    if(in_array($char, $numbers)) {
        $message_keyword = 'includes';
        break; //found, no need to check next
    }   
}

要以更紧凑的形式使用所有逻辑,请使用其他人之前发布的常规表达式。

答案 3 :(得分:1)

更好的方法是使用正则表达式

<?php
    if (preg_match('#[0-9]#',$string)){
        $message_keyword = 'includes';
    }
    else{
        $message_keyword = 'desn\'t include';
    }  
?>

答案 4 :(得分:0)

array range ( mixed $start , mixed $end [, number $step = 1 ] )

如果给出step值,它将用作序列中elements之间的增量。 step应以positive number的形式提供。如果不是指定,则步骤将默认为1

在您的情况下,您还没有提到第三个参数,因此它始终设置为1

请参阅Manual here