Home >Backend Development >PHP Tutorial >php: Comparison of preg_match and preg_match_all usage examples

php: Comparison of preg_match and preg_match_all usage examples

伊谢尔伦
伊谢尔伦Original
2017-06-24 15:35:331841browse

Regular expressionsApplication in PHP

In PHP applications, regular expressions are mainly used for:
•Regular matching: Match the corresponding content according to the regular expression
•Regular replacement: Match the content according to the regular expression and replace
•Regular segmentation: Split the string according to the regular expression
There are two types of regular expression functions in PHP, one is the Perl-compatible regular expression function, and the other is the POSIX extended regular expression function. There is not much difference between the two, and it is recommended to use Perl-compatible regular expression functions, so the following uses Perl-compatible regular expression functions as examples.
Delimiter
Perl compatibility mode regular expression function, its regular expression needs to be written in the delimiter. Any character that is not a letter, number, or backslash () can be used as a delimiter. Usually we use / as the delimiter. See the examples below for specific usage.
Tips
Although regular expressions are very powerful, if it can be completed with ordinary string processing functions, try not to use regular expression functions, because the efficiency of regular expressions will be very low. many. About ordinary string processing functions.
preg_match()
preg_match() function is used for regular expression matching, returning 1 successfully, otherwise returning 0.
Syntax:
int preg_match( string pattern, string subject [, array matches ] )
Parameter description:

Parameter Description
pattern Regular expression
subject Objects that need to be matched to be retrieved
matches Optional, for storing matching results Array, $matches[0] will contain text that matches the entire pattern, $matches[1] will contain text that matches the subpattern in the first captured bracket, 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, due to the use of The i modifier is used, so text matching in php will be case-insensitive.
Tip
preg_match() will stop matching after the first successful match. If you want to match all results, that is, search to the end of the subject, you need to use the preg_match_all() function.
Example 2, obtain the host domain name from a URL:

<?php
// 从 URL 中取得主机名
preg_match("/^(http://)?([^/]+)/i","http://www.php.cn/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "域名为:{$matches[0]}";
?>

Browser output:

Domain name For: php.cn


##preg_match_all()

preg_match_all() function is used for global matching of regular expressions and returns successfully The number of times the entire pattern is matched (possibly zero), or FALSE if an error occurs.

Syntax:
int preg_match_all( string pattern, string subject, array matches [, int flags ] )

Parameter description:

ParametersDescriptionpatternRegular expressionsubjectRequired to match the retrieved objectmatchesArray to store the matching resultsflags
Optional, specify the order in which matching results are placed in matches. The available tags are:

  1. PREG_PATTERN_ORDER: Default, sort the results. Let $matches[0] be an array of all pattern matches, $matches[1] be an array of strings matched by the subpattern in the first bracket, and so on

  2. 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

  3. PREG_OFFSET_CAPTURE: If this flag is set, the associated string offset

will be returned for each matching result. The following example demonstrates displaying the keywords (php) in all e03b848252eb9375d56be284e690e873bc5574f69a0cba105bc93bd3dc13c4ec tags in the text in red.



<?php
$str = "<pre class="brush:php;toolbar:false">学习php是一件快乐的事。
所有的phper需要共同努力!
"; $kw = "php"; preg_match_all('/
([sS]*?)
/',$str,$mat); for($i=0;$i'.$kw.'', $mat[0][$i]); $str = str_replace($mat[1][$i], $mat[0][$i], $str); } echo $str; ?>

Regular matching Chinese characters
Regular matching Chinese characters are slightly different depending on the page encoding:

•GBK/GB2312 encoding: [x80-xff>]+ or [xa1-xff]+•UTF-8 encoding: [x{4e00}-x{9fa5}]+/u

Example:

<?php
$str = "学习php是一件快乐的事。";
preg_match_all("/[x80-xff]+/", $str, $match);
//UTF-8 使用:
//preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match);
print_r($match);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 学习
            [1] => 是一件快乐的事。
        )
)


The above is the detailed content of php: Comparison of preg_match and preg_match_all usage examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn