PHP preg_match查找多次出现 [英] PHP preg_match to find multiple occurrences
本文介绍了PHP preg_match查找多次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在PHP中使用preg_match查找正则表达式的多次出现的正确语法是什么?
What is the correct syntax for a regular expression to find multiple occurrences of the same string with preg_match in PHP?
例如,在下面的段落中查找以下字符串是否出现了TWICE:
For example find if the following string occurs TWICE in the following paragraph:
$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";
}
推荐答案
您要使用 $matches
数组将保存结果:
You want to use 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:
<?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个匹配项
2 matches found
这篇关于PHP preg_match查找多次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文