php中,preg_match_all()函数用于执行一个全局正则表达式匹配,可以搜索字符串中所有可以和正则表达式匹配的结果,语法“preg_match_all(pattern,subject,matches,flags,offset)”。
本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑
preg_match_all()函数可以搜索字符串中所有可以和正则表达式匹配的结果,语法格式如下:
preg_match_all(pattern,subject,matches,flags,offset)
参数说明如下:
preg_match_all() 函数可以返回 pattern 的匹配次数(可能是 0),如果发生错误则返回 FALSE。
示例1:使用 preg_match_all() 函数匹配一个字符串。
<?php $subject = "abcdefghijkdefabcedfdefxyzdef"; $pattern_1 = '/(def)(abc)/'; $num_1 = preg_match_all($pattern_1, $subject, $matches_1,PREG_PATTERN_ORDER); echo "<pre class="brush:php;toolbar:false">"; var_dump($matches_1); var_dump($num_1); $pattern_2 = '/(def)(abc)/'; $num_2 = preg_match_all($pattern_2, $subject, $matches_2,PREG_OFFSET_CAPTURE, 3); var_dump($matches_2); var_dump($num_2); ?>
运行结果如下:
array(3) { [0]=>array(1) { [0]=>string(6) "defabc" } [1]=>array(1) { [0]=>string(3) "def" } [2]=>array(1) { [0]=>string(3) "abc" } } int(1) array(3) { [0]=>array(1) { [0]=>array(2) { [0]=>string(6) "defabc" [1]=>int(11) } } [1]=>array(1) { [0]=>array(2) { [0]=>string(3) "def" [1]=>int(11) } } [2]=>array(1) { [0]=>array(2) { [0]=>string(3) "abc" [1]=>int(14) } } } int(1)
示例2:查找匹配的HTML标签(贪婪):
<?php //\\2是一个后向引用的示例. 这会告诉pcre它必须匹配正则表达式中第二个圆括号(这里是([\w]+)) //匹配到的结果. 这里使用两个反斜线是因为这里使用了双引号. $html = "<b>bold text</b><a href=howdy.html>click me</a>"; preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER); foreach ($matches as $val) { echo "matched: " . $val[0] . "\n"; echo "part 1: " . $val[1] . "\n"; echo "part 2: " . $val[2] . "\n"; echo "part 3: " . $val[3] . "\n"; echo "part 4: " . $val[4] . "\n\n"; } ?>
执行结果如下所示:
matched: <b>bold text</b> part 1: <b> part 2: b part 3: bold text part 4: </b> matched: <a href=howdy.html>click me</a> part 1: <a href=howdy.html> part 2: a part 3: click me part 4: </a>
推荐学习:《PHP视频教程》
The above is the detailed content of How to use preg_match_all() in php. For more information, please follow other related articles on the PHP Chinese website!