2010-01-08 130 views
7

正則表達式在PHP中使用preg_match查找多個匹配的字符串的正確語法是什麼?PHP preg_match找到多個匹配

例如,如果發現以下段落中出現兩次以下字符串:

$string = "/brown fox jumped [0-9]/"; 

$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence" 

if (preg_match($string, $paragraph)) { 
echo "match found"; 
}else { 
echo "match NOT found"; 
} 
+0

以http嘗試:// WWW .regex-tester.de/regex.html – Gordon 2010-01-08 19:06:47

回答

23

你想用​​。這是它在代碼中的外觀。實際的函數返回找到的項目數,但$matches陣列將持有的結果:

<?php 
$string = "/brown fox jumped [0-9]/"; 

$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence"; 

if (preg_match_all($string, $paragraph, &$matches)) { 
    echo count($matches[0]) . " matches found"; 
}else { 
    echo "match NOT found"; 
} 
?> 

將輸出:

2場比賽中

+0

我收到警告呼叫時間通過引用已被棄用。 – Dipen 2015-09-27 09:44:34

+5

從「&$ matches」中移除「&」 – Sam 2015-12-09 10:56:25