Php regular greedy matching and non-greedy matching examples

Source: Internet
Author: User
Tags regular expression

The principles of greedy pattern matching are as follows:

In the case of matching or mismatch, the matching is prioritized until the matching is successful, the alternative status is recorded, and the matching control is handed over to the next matching character of the regular expression, when the subsequent matching fails, you can trace back and perform the matching.
It will match as many characters as possible. It first looks at the entire string. If it does not match, the string is reduced. If it encounters a possible match, it stops shrinking and expands the text. When a matching text is found, it does not rush to save the match to the matching set, but expands the text until it cannot continue matching or expand the complete string, save the Last matched text (also the longest) to the matching set. So it is greedy.

Example:

The preg_match function returns the first matched string.
The following strings are available:

The code is as follows: Copy code
$ Str = "Nothing can <B> replace </B> a <B> mother </B>'s love ."

Now you want to obtain the content of the first <B> replace </B>.

1. Greedy match

The code is as follows: Copy code

<? Php
$ Str = "Nothing can <B> replace </B> a <B> mother </B>'s love .";
 
// Greedy match returns the largest string
$ IsMatch = preg_match ('/<B> (. *) </B>/', $ str, $ match );
If ($ IsMatch ){
Print_r ($ match). "n ";
}
/*
Output:
Array
(
   
[0] => <B> replace </B> a <B> mother </B>
   
[1] => replace </B> a <B> mother
)
*/
?>

No expected content. Greedy match returns the largest string.

Non-greedy match


"?" When this character is followed by any other delimiter (*, + ,?, The matching mode after {n}, {n ,}, {n, m}) is not greedy. The non-greedy mode matches as few searched strings as possible, while the default greedy mode matches as many searched strings as possible. For example, for strings "oooo", 'O ++? 'Will match a single "o", and 'O +' will match all 'o '.

Example:

The code is as follows: Copy code

Preg_replace ('/<td (. *?)> /I ',' <td> ', $ str); // match the first ">" after "<td ";

Preg_replace ('/<td (. *)>/I ',' <td> ', $ str); // match the last ">" after "<td ";


Preg_replace ('/<td (. *?)> /I ',' <td> ', $ str); // match the first ">" after "<td "; it is also equivalent to preg_replace ('/<td (. *)>/isU ',' <td> ', $ str );

 

In addition: use $1, $2 ...... $9 can extract values from.


There are two methods to use the modifier U or ?.

The code is as follows: Copy code

<? Php
$ Str = "Nothing can <B> replace </B> a <B> mother </B>'s love .";
 
// Use? Returns the smallest string for non-greedy match.
$ IsMatch = preg_match ('/<B> (.*?) </B>/', $ str, $ match );
If ($ IsMatch ){
Print_r ($ match). "n ";
}
/*
Output:
Array
(
   
[0] => <B> replace </B>
   
[1] => replace
)
*/
 
?>

Check again

The code is as follows: Copy code


<? Php
$ Str = "Nothing can <B> replace </B> a <B> mother </B>'s love .";
 
// Returns the smallest string using U non-greedy match
$ IsMatch = preg_match ('/<B> (. *) </B>/U', $ str, $ match );
If ($ IsMatch ){
Print_r ($ match). "n ";
}
/*
Output:
Array
(
   
[0] => <B> replace </B>
   
[1] => replace
)
*/
 
?>

Non-greedy match to get the desired result

Example

For example:

String:... src = "http://www.111cn.net/1.mp3" type = "application/x-mplayer2 "....
Requirement results: http://www.111cn.net/1.mp3

If the matching expression is written as:/src = "(. *)"/, no correct result is obtained because the matching of the last double quotation mark is greedy.

Solution: write the matching expression as follows:

The code is as follows: Copy code
/Src = "(.*)".? /

In the above expression ,".? Non-greedy pattern matching. That is to say, as long as a character is followed by a specified number of special characters, matching is a non-greedy mode.

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.