Small php experience: parsing functions preg_match and preg_match_all

Source: Internet
Author: User

Application of Regular Expressions in PHP
In PHP applications, regular expressions are mainly used:
• Regular Expression matching: matches the corresponding content according to the regular expression.
• Regular Expression replacement: Match and replace the content according to the regular expression.
• Regular Expression segmentation: splits strings based on regular expressions.
There are two types of Regular Expression functions in PHP: Perl-Compatible Regular Expression functions and POSIX-extended regular expression functions. There is little difference between the two, and Perl is recommended to be compatible with regular expression functions. Therefore, the following uses Perl Compatible Regular Expression functions as an example.
Delimiters
Regular Expression functions in Perl compatibility mode. The regular expression must be written in the delimiters. Any character that is not a letter, number, or backslash () can be used as a separator. We usually use/as a delimiter. For more information, see the following example.
Prompt
Although regular expressions are very powerful, do not use regular expression functions if common string processing functions can be completed, because regular expressions are much less efficient. About common string processing functions.
Preg_match ()
The preg_match () function is used for regular expression matching. If the regular expression matches successfully, 1 is returned. Otherwise, 0 is returned.
Syntax:
Int preg_match (string pattern, string subject [, array matches])
Parameter description:

Parameters Description
Pattern Regular Expression
Subject Objects to be retrieved
Matches (Optional) an array storing the matching results. $ matches [0] will contain the text that matches the entire pattern, $ matches [1] will contain the text that matches the child pattern in the first captured bracket, and so on

Example 1:
Copy codeThe Code is as follows: <? 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:
Copy codeThe Code is as follows: A match was found: PHP

In this example, the I modifier is used to match php in text without case sensitivity.
Prompt
Preg_match (): After the first successful match, the match will stop. If you want to match all the results, that is, find the end of the subject, you need to use the preg_match_all () function.
Example 2: Obtain the host domain name from a URL:
Copy codeThe Code is as follows: <? Php
// Obtain the host name from the URL
Preg_match ("/^ (http ://)? ([^/] +)/I "," http://www.jb51.net/index.html ", $ matches );
$ Host = $ matches [2];
// Obtain the following two segments from the host name
Preg_match ("/[^./] +. [^./] + $/", $ host, $ matches );
Echo "Domain Name: {$ matches [0]}";
?>

Browser output:
Copy codeThe Code is as follows: Domain Name: jb51.net

Preg_match_all ()
The preg_match_all () function is used to perform global matching of regular expressions. If the regular expression is successfully matched, the number of times (which may be zero) is returned. If an error occurs, FALSE is returned.
Syntax:
Int preg_match_all (string pattern, string subject, array matches [, int flags])
Parameter description:

Parameters Description
Pattern Regular Expression
Subject Objects to be retrieved
Matches Array storing matching results
Flags

Optional. Specify the order in which the matching results are placed in matches. The available tags are:

  1. PREG_PATTERN_ORDER: default value. Sort the result to $ matches [0] as an array of all pattern matching. $ matches [1] is an array consisting of strings matched by the Child pattern in the first bracket, and so on.
  2. PREG_SET_ORDER: sort the result to $ matches [0] As the array of the first matching item, $ matches [1] As the array of the second matching item, and so on.
  3. PREG_OFFSET_CAPTURE: If this tag is set, the offset of the affiliated string is also returned for each matching result.

The following example shows that the keywords (php) in all <pre> </pre> labels in the text are displayed in red.Copy codeThe Code is as follows: <? Php
$ Str = "<pre> learning php is a pleasure. </Pre> <pre> All phper needs 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;
?>

Regular Expression matching Chinese Characters
Regular Expression matching Chinese characters are slightly different based on the page encoding:
• GBK/GB2312: [x80-xff>] + or [xa1-xff] +
• UTF-8 code: [x {4e00}-x {9fa5}] +/u
Example:
Copy codeThe Code is as follows: <? Php
$ Str = "Learning php is a pleasure. ";
Preg_match_all ("/[x80-xff] +/", $ str, $ match );
// UTF-8 use:
// Preg_match_all ("/[x {4e00}-x {9fa5}] +/u", $ str, $ match );
Print_r ($ match );
?>

Output:
Copy codeThe Code is as follows: Array
(
[0] => Array
(
[0] => Learning
[1] => is a happy thing.
)

)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.