Yesterday encountered the problem, in the BBS asked to come to the agreed as follows./(. +?) B/is non-greedy pattern matching AB/(. *) b/is is greedy pattern matching ABB,
So let's take a look at the basic symbolic description:
* 0 times, 1 times or more to match the atoms before them
+ 1 or more times to match the atoms before it
? 0 times or 1 times to match the atoms before them
. Matches any character other than a newline
Let's take a look at a simple example:
You test. +? and. * Of course I don't see the difference.
Test this string to see
' Aaa<div style= ' font-color:red; >123456</DIV>BBB '
<.+?> will match <div style= "font-color:red;" > and </div>
<.*> will match <div style= "font-color:red;" >123456</div>
Finally see what the master said.
(. +) Default this is greedy match
Greed is the first to see whether the whole string is matched, if it does not match, it will remove the last character of the string and try again, if it does not match, then remove the current last one until it finds a match or no characters left.
The process is probably like this:
$str = ' Abcdabceba '
/.+b///Match one or more arbitrary characters followed by a letter B
The first time (see if the entire string is a match) Abcdabceba does not match and then the last character is removed
Second (remove last character and then match) ABCDABCEB exit correctly
Inertia is the first character from the left to start matching, first to see if the first character is a match, if not match to add the next character and then taste the match until the match found ...
The process is probably like this
$str = ' Abcdabceba '
/.+?b///also matches one or more arbitrary characters followed by a letter B
First (read into the left of the first character) a mismatch plus one more
The second AB match is recorded and continues (if all words are matched, such as Preg_match_all, or preg_replace, not all stop here.
Third time C
...
Cdab match record down and continue
...
CEB match record down and continue
A to the end, no exit.
Simple example:
<?php
//Here because there is no use of all,. +? Match only once
$str=' Abcdabceba ';
Preg_match('/.+b/', $str, $s);
Echo$s[0]; //ABCDABCEB
Echo" ";
Preg_match('/.+?b/', $str, $s);
Echo$s[0]; //AB
Echo" ";
Preg_match('/.+b/u ', $str, $s); Equal to/.+?b/
Echo$s[0]; //ab
?>