preg_match_all没有做我期待它做的事情?

时间:2011-08-12 07:08:25

标签: php regex count preg-match-all

这段代码对我来说似乎非常简单和合乎逻辑,我必须感到厌倦,因为它没有按照我的预期行事......

//look for any letter, number or underscore    
$regexTags = "/[a-z0-9_]/i";

//needlessly large string..
$string = "111 222 333 444 555 666 777";
preg_match_all($regexTags, $string, $regexMatches);
print_r($regexMatches);

//$regexMatches spits out  [0] => Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 2 [5] => 2 [6] => 3 [7] => 3 [8] => 3 [9] => 4 [10] => 4 [11] => 4 [12] => 5 [13] => 5 [14] => 5 [15] => 6 [16] => 6 [17] => 6 [18] => 7 [19] => 7 [20] => 7))
//as expected.

//Count how many variables are in the array 
$matchCount = count($regexMatches);

if ($matchCount < 5){
    echo "less than 5";
}

为什么仍然会打印“小于5”,即使$ regexMatches数组中有20个值非常明显?我做错了什么?

2 个答案:

答案 0 :(得分:4)

尝试count($regexMatches[0])

:)

答案 1 :(得分:3)

为什么你不能使用preg_match_all返回值:

$matchCount = preg_match_all($regexTags, $string, $regexMatches);
echo $matchCount;