PHP的preg_match()和preg_match_all()函数

54

3
你已经查看了PHP文档吗?http://www.php.net/manual/zh/function.preg-match.php 和 http://www.php.net/manual/zh/function.preg-match-all.php。请阅读这些文档以获取更多信息。 - Philip
5
@Philip: 是的,我看了,但是我没理解它。 - sikas
文档并没有解释这两者之间的区别。需要花一点时间阅读,但此处其他人给出的答案节省了很多时间。 - MaXi32
3个回答

147

preg_match在找到第一个匹配项后就停止查找。而preg_match_all则会继续查找,直到处理完整个字符串为止。一旦找到匹配项,它会使用剩余的字符串来尝试应用另一个匹配项。

http://php.net/manual/zh/function.preg-match-all.php


10
谢谢,你的回答对我比选中的那个更有用,因为你实际上简化了文档的解释。再次感谢! - Alexandre TryHard Leblanc

20

PHP中的preg_matchpreg_match_all函数都使用与Perl兼容的正则表达式。

您可以观看这个系列视频,全面了解Perl兼容的正则表达式:https://www.youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w

preg_match($pattern, $subject, &$matches, $flags, $offset)

preg_match函数用于在$subject字符串中搜索特定的$pattern,当找到第一个匹配项时,停止搜索。它会输出匹配结果到$matches中,其中$matches[0]包含与完整模式匹配的文本,$matches[1]包含与第一个捕获括号内的子模式匹配的文本,以此类推。

preg_match()示例

<?php
preg_match(
    "|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $matches
);

var_dump($matches);

输出:

array(2) {
  [0]=>
  string(16) "<b>example: </b>"
  [1]=>
  string(9) "example: "
}

preg_match_all($pattern, $subject, &$matches, $flags)

preg_match_all函数在一个字符串中搜索所有匹配项,并将它们按照$flags的顺序输出到一个多维数组($matches)中。当没有传递$flags值时,它会按照一定的顺序排列结果,使得$matches[0]是一个包含完整模式匹配的数组,$matches[1]是第一个括号子模式匹配的字符串数组,以此类推。

preg_match_all()示例

<?php
preg_match_all(
    "|<[^>]+>(.*)</[^>]+>|U",
    "<b>example: </b><div align=left>this is a test</div>",
    $matches
);

var_dump($matches);

输出:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(16) "<b>example: </b>"
    [1]=>
    string(36) "<div align=left>this is a test</div>"
  }
  [1]=>
  array(2) {
    [0]=>
    string(9) "example: "
    [1]=>
    string(14) "this is a test"
  }
}

8
一个具体的例子:
preg_match("/find[ ]*(me)/", "find me find   me", $matches):
$matches = Array(
    [0] => find me
    [1] => me
)

preg_match_all("/find[ ]*(me)/", "find me find   me", $matches):
$matches = Array(
    [0] => Array
        (
            [0] => find me
            [1] => find   me
        )

    [1] => Array
        (
            [0] => me
            [1] => me
        )
)

preg_grep("/find[ ]*(me)/", ["find me find    me", "find  me findme"]):
$matches = Array
(
    [0] => find me find    me
    [1] => find  me findme
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接