简体   繁体   English

PHP preg_match查找多次出现

[英]PHP preg_match to find multiple occurrences

What is the correct syntax for a regular expression to find multiple occurrences of the same string with preg_match in PHP? 正则表达式使用PHP中的preg_match查找多次出现的相同字符串的正确语法是什么?

For example find if the following string occurs TWICE in the following paragraph: 例如,查找以下段落中是否在TWICE中出现以下字符串:

$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";
}

You want to use preg_match_all() . 您想使用preg_match_all() Here is how it would look in your code. 这就是代码中的样子。 The actual function returns the count of items found, but the $matches array will hold the results: 实际函数返回找到的项目数,但是$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";
}
?>

Will output: 将输出:

2 matches found 找到2个匹配项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM