PHP regular expression greedy mode and lazy mode greedy mode when a regular expression contains a qualifier that can accept duplicates, the common behavior is (on the premise that the entire expression can be matched) match as many characters as possible. Consider this expression: a. * B, which will match the longest string starting with a and ending with B. If you use it to search for aabab, it will match the entire string aabab. This is called greedy matching. Lazy pattern sometimes, we need more lazy matching, that is, matching as few PHP regular greedy pattern and lazy pattern as possible.
Greedy mode
When a regular expression contains a qualifier that can accept duplicates, the common behavior is to match as many characters as possible (on the premise that the entire expression can be matched.
Consider this expression: a. * B, which will match the longest string starting with a and ending with B. If you use it to search for aabab, it will match the entire string aabab. This is called greedy matching.
Lazy mode
Sometimes, we need to be more lazy to match, that is, to match as few characters as possible. All the qualifiers given above can be converted to the lazy match mode, as long as a question mark is added after it ?. This way .*? This means to match any number of duplicates, but use the minimum number of duplicates if the entire match is successful. Now let's look at the lazy version example:
A .*? B matches the string that is shortest, starts with a, and ends with B. If it is applied to aabab, it will match aab (first to third character) and AB (fourth to fifth character ).
Example 2
Request string: src = "http://www.bloghome.cn/1.mp3" type = "application/x-mplayer2" found matching result: http://www.bloghome.cn/1.mp3
If the matching expression is written as follows:
/Src = "(.*)"/,
$str ='src="http://www.bloghome.cn/1.mp3" type="application/x-mplayer2"'; preg_match('/src="(.*)"/', $str, $matches);
The result of $ matches [1] is as follows:
Http://www.bloghome.cn/1.mp3 "type =" application/x-mplayer2Because the matching of the last double quotes is greedy.
If the matching expression is written as follows:
/Src = "(.*?) "/, And the result of $ matches [1] is
Http://www.bloghome.cn/1.mp3
End Separator/subsequent meaning
Note: If pattern is used
Reference
/I indicates case insensitive
/S indicates. it also matches white space characters
/U indicates that the pattern is reversed, that is, the greedy match pattern is changed to the lazy match pattern, and the lazy match pattern is changed to the greedy match pattern.