Home  >  Article  >  Backend Development  >  How to use php preg_match_all function

How to use php preg_match_all function

藏色散人
藏色散人Original
2019-05-27 09:38:483715browse

php preg_match_all函数用于执行一个全局正则表达式匹配,返回完整匹配次数(可能是0),或者如果发生错误返回FALSE。

How to use php preg_match_all function

php preg_match_all函数怎么用?

preg_match_all 函数用于执行一个全局正则表达式匹配。

语法

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

搜索 subject 中所有匹配 pattern 给定正则表达式的匹配结果并且将它们以 flag 指定顺序输出到 matches 中。

在第一个匹配找到后, 子序列继续从最后一次匹配位置搜索。

参数说明:

$pattern: 要搜索的模式,字符串形式。

$subject: 输入字符串。

$matches: 多维数组,作为输出参数输出所有匹配结果, 数组排序通过flags指定。

$flags:可以结合下面标记使用(注意不能同时使用PREG_PATTERN_ORDER和 PREG_SET_ORDER):

PREG_PATTERN_ORDER: 结果排序为$matches[0]保存完整模式的所有匹配, $matches[1] 保存第一个子组的所有匹配,以此类推。

PREG_SET_ORDER: 结果排序为$matches[0]包含第一次匹配得到的所有匹配(包含子组), $matches[1]是包含第二次匹配到的所有匹配(包含子组)的数组,以此类推。

PREG_OFFSET_CAPTURE: 如果这个标记被传递,每个发现的匹配返回时会增加它相对目标字符串的偏移量。

offset: 通常, 查找时从目标字符串的开始位置开始。可选参数offset用于 从目标字符串中指定位置开始搜索(单位是字节)。

返回值

返回完整匹配次数(可能是0),或者如果发生错误返回FALSE。

实例

查找匹配 a4b561c25d9afb9ac8dc4d70affff419 与 0d36329ec37a2cc24d42c7229b69747a 标签的内容:

<?php
$userinfo = "Name: <b>PHP</b> <br> Title: <b>Programming Language</b>";
preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
print_r($pat_array[0]);
?>

执行结果如下所示:

Array
(
    [0] => <b>PHP</b>
    [1] => <b>Programming Language</b>
)

查找匹配的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>

The above is the detailed content of How to use php preg_match_all function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn