PHP preg_match and preg_match_all functions

后端 未结 3 1396
野性不改
野性不改 2020-12-01 05:14

I would like to know what the preg_match and preg_match_all functions do and how to use them.

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 05:46

    Both preg_match and preg_match_all functions in PHP use Perl compatible regular expressions.

    You can watch this series to fully understand Perl compatible regular expressions: https://www.youtube.com/watch?v=GVZOJ1rEnUg&list=PLfdtiltiRHWGRPyPMGuLPWuiWgEI9Kp1w

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

    The preg_match function is used to search for a particular $pattern in a $subject string and when the pattern is found the first time, it stops searching for it. It outputs matches in the $matches, where $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized sub-pattern, and so on.

    Example of preg_match()

    ]+>(.*)]+>|U",
        "example: 
    this is a test
    ", $matches ); var_dump($matches);

    Output:

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

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

    The preg_match_all function searches for all the matches in a string and outputs them in a multi-dimensional array ($matches) ordered according to $flags. When no $flags value is passed, it orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized sub-pattern, and so on.

    Example of preg_match_all()

    ]+>(.*)]+>|U",
        "example: 
    this is a test
    ", $matches ); var_dump($matches);

    Output:

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

提交回复
热议问题