PHP preg_match和preg_match_all函数

sik*_*kas 38 php preg-match-all preg-match

我想知道它们preg_matchpreg_match_all功能的用途以及如何使用它们.

rom*_*nsh 108

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

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

  • 谢谢,这个答案对我来说比选择的答案更有用,因为你实际上简化了文档解释它的方式.再次感谢! (8认同)

小智 13

双方的preg_matchpreg_match_all PHP函数使用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);
Run Code Online (Sandbox Code Playgroud)

输出:

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

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);
Run Code Online (Sandbox Code Playgroud)

输出:

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"
  }
}
Run Code Online (Sandbox Code Playgroud)


Reb*_*cca 6

一个具体的例子:

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
)
Run Code Online (Sandbox Code Playgroud)