php lesson: Parse preg_match and preg_match_all functions

  • 2020-06-23 00:03:36
  • OfStack

Application of regular expressions in PHP
In PHP applications, regular expressions are mainly used for:
The & # 8226; Regular matching: Matches the corresponding content according to the regular expression
The & # 8226; Regular replacement: Matches content against a regular expression and replaces it
The & # 8226; Regular splitting: Splitting a string according to a regular expression
There are two types of regular expression functions in PHP, one is Perl compatible regular expression function and the other is POSIX extended regular expression function. There is little difference between the 2, and Perl compatible regular expression functions are recommended. Therefore, Perl compatible regular expression functions are taken as examples to illustrate below.
delimiter
Perl mode compliant regular expression functions, whose regular expressions need to be written in delimiters. Any character that is not a letter, number, or backslash () can be used as a delimiter, usually we use/as a delimiter. See the following example for specific use.
prompt
Although regular expressions are very powerful, avoid regular expression functions if they can be done with normal string handling functions, because regular expressions are much less efficient. About ordinary string handlers.
preg_match()
The preg_match() function is used for a regular expression match that returns 1 on success or 0 on failure.
Grammar:
int preg_match( string pattern, string subject [, array matches ] )
Parameter description:
parameter instructions pattern Regular expression subject The retrieved object needs to be matched matches Optionally, store an array of matching results, $matches[0] will contain the text that matches the entire pattern, $matches[1] will contain the text that matches the subpattern in the first captured parenthesis, and so on: Example 1:

<?php
if(preg_match("/php/i", "PHP is the web scripting language of choice.", $matches)){
    print "A match was found:". $matches[0];
} else {
    print "A match was not found.";
}
?>

Browser output:

A match was found: PHP

In this example, because the i modifier is used, matching php in the text is case-insensitive.
prompt
preg_match() will stop after the first match, and the preg_match_all() function will be used if all results are matched, i.e. the end of subject is searched.
Example 2: Get the host domain name from 1 URL:

<?php
//  from  URL  Gets the host name 
preg_match("/^(http://)?([^/]+)/i","https://www.ofstack.com/index.html", $matches);
$host = $matches[2];
//  Get the next two paragraphs from the host name 
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo " Domain name is: {$matches[0]}";
?>

Browser output:

 Domain name is: ofstack.com

preg_match_all()
The preg_match_all() function is used for global regular expression matches, returning the number of successful (possibly zero) matches for the entire pattern, and FALSE if there is an error.
Grammar:
int preg_match_all( string pattern, string subject, array matches [, int flags ] )
Parameter description:
parameter instructions pattern Regular expression subject The retrieved object needs to be matched matches Store an array of matching results flags

Optionally, specify the order in which the matching results are put into matches. The optional tags are:

PREG_PATTERN_ORDER: By default, the results are sorted so that $matches[0] is an array of all pattern matches, $matches[1] is an array of strings matched by subpatterns in the first bracket, and so on PREG_SET_ORDER: Sort the results so that $matches[0] is the array of the first set of matches, $matches[1] is the array of the second set of matches, and so on PREG_OFFSET_CAPTURE: If this tag is set, an attached string offset is also returned for each occurrence of a match < pre > < /pre > Keywords within the tag (php) appear in red.

<?php
$str = "<pre> learning php is 1 A happy thing. </pre><pre> All of the phper Need to work together! </pre>";
$kw = "php";
preg_match_all('/<pre>([sS]*?)</pre>/',$str,$mat);
for($i=0;$i<count($mat[0]);$i++){
    $mat[0][$i] = $mat[1][$i];
    $mat[0][$i] = str_replace($kw, '<span style="color:#ff0000">'.$kw.'</span>', $mat[0][$i]);
    $str = str_replace($mat[1][$i], $mat[0][$i], $str);
}
echo $str;
?>

Regex matches Chinese characters
Regular matching Chinese characters are slightly different according to the page encoding:
The & # 8226; GBK/GB2312 en101EN80-xff > [xa1] + or - xff] +
The & # 8226; Code: [x{4e00}-x{9fa5}]+/u
Example:

<?php
$str = " learning php is 1 A happy thing. ";
preg_match_all("/[x80-xff]+/", $str, $match);
//UTF-8  Use: 
//preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match);
print_r($match);
?>

Output:

Array
(
    [0] => Array
        (
            [0] =>  learning 
            [1] =>  is 1 A happy thing. 
        )

)

Related articles: