题
什么是正确的语法使用正则表达式查找相同的字符串多次出现用的preg_match在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($string, $paragraph)) {
echo "match found";
}else {
echo "match NOT found";
}
解决方案
您想使用 preg_match_all()
。下面是它会怎样看在你的代码。实际函数返回找到的项的计数,但$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个匹配
不隶属于 StackOverflow