【问题标题】:PHP's preg_match() and preg_match_all() functionsPHP preg_match() 和 preg_match_all() 函数
【发布时间】:2022-02-23 10:35:46
【问题描述】:

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

【问题讨论】:

标签: php preg-match preg-match-all


【解决方案1】:

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

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

【讨论】:

  • 谢谢,这个答案对我来说比选择的答案更有用,因为你实际上简化了文档解释它的方式。再次感谢!
【解决方案2】:

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"
  }
}

【讨论】:

    【解决方案3】:

    一个具体的例子:

    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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多