0

我正在尝试使用正则表达式制作一个程序来匹配必须包含 0-9 数字的字符串。这是正确的,但不知何故似乎很长。有没有人有这个代码的替代品?

if($str = (preg_match('/[1]/', $str) && preg_match('/[2]/', $str)     
  && preg_match('/[3]/', $str) && preg_match('/[4]/', $str)     
  && preg_match('/[5]/', $str) && preg_match('/[6]/', $str)     
  && preg_match('/[7]/', $str) && preg_match('/[8]/', $str)     
  && preg_match('/[9]/', $str) && preg_match('/[0]/', $str))) {
    //do something
}
4

3 回答 3

2

只需使用字符范围:[0-9].

if (preg_match('/[0-9]/', $str)) {
    echo 'It does.';
} else {
    echo 'It doesn\'t.';
}

如果您曾经遇到过不想要“6”的情况,您甚至可以将其更改为[012345789]如果您真的想要的话。


正如弗洛里斯所提到的,您的代码非常混乱 - 如果您希望所有字符至少单独显示一次,您可以简单地使用strpos循环:

<?php
    $match = true;
    for ($i = 0; $i < 9; $i++) {
        if (strpos($string, (string)$i) === false) {
            $match = false;
            break; //No need to continue the loop - we already got our answer
        }
    }

    if ($match) {
        echo 'Yes!';
    } else {
        echo 'No!';
    }
?>

或者,我显然已经给了你一个功能来做到这一点?

于 2013-11-13T13:50:25.720 回答
1

看起来您将所有条件与运算结合在一起。在以下基于前瞻的正则表达式中应该适合您:

preg_match('/(?=[^0]*0)(?=[^1]*1)(?=[^2]*2)(?=[^3]*3)(?=[^4]*4)(?=[^5]*5)(?=[^6]*6)(?=[^7]*7)(?=[^8]*8)(?=[^9]*9)./', $str)
于 2013-11-13T13:55:41.867 回答
1

如果你想确保你的字符串包含所有数字0-9,你可能应该去掉任何不是数字的东西,然后只取唯一字符,并确保字符串长度为 10。这比你的表达式更紧凑,但不一定快点。php 函数count_chars完成了大部分工作(使用mode = 3):

$str = "12345abcde789d9999969";
preg_match_all('/\d+/', $str, $matches);
$distinct = strlen(count_chars(join($matches[0]),3));
if($distinct==10)
{
  echo "all ten digits are present<br>";
}
else 
{
  echo "not all digits are present<br>";
}
echo "there are " . $distinct . " distinct digits<br>";

上述输出:

not all digits are present
there are 9 distinct digits
于 2013-11-13T14:40:35.173 回答