52

preg_match()preg_match_all()函数有什么作用以及如何使用它们?

4

3 回答 3

137

preg_match停止照顾第一场比赛。preg_match_all另一方面,它会继续查找,直到完成整个字符串的处理。一旦找到匹配项,它就会使用字符串的其余部分来尝试应用另一个匹配项。

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

于 2013-11-04T12:05:46.663 回答
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函数用于搜索字符串中的特定$pattern内容$subject,当第一次找到该模式时,它会停止搜索。它在 中输出匹配项$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的多维数组 ( ) 中。当没有传递任何值时,它对结果进行排序,以便它是一个完整模式匹配的数组,是一个与第一个带括号的子模式匹配的字符串数组,依此类推。$matches$flags$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"
  }
}
于 2016-05-20T13:03:28.367 回答
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
)
于 2016-05-18T14:08:29.803 回答