2011-08-12 57 views
0

此代碼似乎很容易和邏輯給我,我一定是因爲它沒有做什麼,我希望它是累了..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」仍在即使印刷雖然有相當清楚的20 $ regexMatches數組中的值?我究竟做錯了什麼?

回答

4

嘗試count($regexMatches[0])

:)

+1

GAUGHHHGHGHGHGHGHHGHGHGHGHGHGHGHGH! *把頭髮拉出來*我花了兩個小時的時間試圖弄清楚這一點,而不必在一段時間內打擾堆棧溢出的好人。謝謝,那就是答案。 – Partack

+1

嘿,很高興幫助。我知道我們都發生了這種情況:p – Kokos

3

爲什麼不能你只需要使用preg_match_all返回值:

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

噢,這只是一個例子來解釋我的問題,最簡單的形式=)我的項目代碼看起來不同於這個=)感謝您的建議,儘管^^ – Partack

+0

哦,第二個想法,我沒有嘗試過這個,它很好地整理了我的代碼。乾杯。 =) – Partack

+1

這很好,當你不需要額外的性能表現:D – Vytautas