2010-01-08 127 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