Differences and usage of preg_match and preg_match_all

Source: Internet
Author: User

Regular expressions are used 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.

The regular expression function in Perl compatibility mode. The regular expression must be written in the regular expression. Any character that is not a letter, number, or backslash () can be used as a separator. We usually use/as a delimiter. Details

For usage, see the example below.

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. For common string processing functions, see 《

PHP string processing.

The preg_match () function is used to match a regular expression. If 1 is successful, 0 is returned.

Syntax:

Int preg_match (string pattern, string subject [, array matches]) parameter description: parameter description
Pattern regular expression
The subject must match the retrieved object.
(Optional) matches. It stores 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 child pattern in the first captured bracket, and so on

Example 1:

The code is as follows: Copy code

<? 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:

Example

<B> example: </B>, <div align = left> this is a test </div>
Example:, this is a test

The code is as follows: Copy code


Preg_match_all ("| <[^>] +> (. *) </[^>] +> | u ",
"<B> example: </B> <div align =" left "> this is a test </div> ",
$ Out, preg_set_order );
Echo $ out [0] [0]. ",". $ out [0] [1]. "n ";
Echo $ out [1] [0]. ",". $ out [1] [1]. "n ";

 

Int preg_match (string $ pattern, string $ subject [, array & $ matches [, int $ flags [, int $ offset])
Search topic frequently expressed in combination

 

The code is as follows: Copy code

$ Subject = "abcdefwww.111cn.net ";
$ Pattern = '/^ def /';
Preg_match ($ pattern, substr ($ subject, 3), $ matches, preg_offset_capture );
Print_r ($ matches );


Array
(
[0] => array
        (
[0] => def
[1] => 0
        )

)

In this example, PHP uses the I modifier 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:

The code is as follows: Copy code

<? Php
// Obtain the host name from the URL
Preg_match ("/^ (http ://)? ([^/] +)/I ", http://www.111cn.net, $ matches );
$ Host = $ matches [2];
// Obtain the following two segments from the host name
Preg_match ("/[^./] +. [^./] + $/", $ host, $ matches );
Echo "domain name: {$ matches [0]}";
?>


Browser output:

The domain name is 5idev. compreg_match_all () preg_match_all (). This 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: parameter description
Pattern regular expression
The subject must match the retrieved object.
Matches stores an array of matching results
(Optional) flags. It specifies the order in which the matching results are placed in matches. The available tags include:

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

The code is as follows: Copy code
<? 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:

The code is as follows: Copy code

<? 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:

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.