Reputation: 10390
I came across the following code that has a regular expression which I do not understand.
Specifically:
'#<!-- START '. $tag . ' -->(.+?)<!-- END '. $tag . ' -->#si'
PHP says that the function 'preg_match' will return the following:
" If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. "
I take it that
(.+?)
is such a 'parenthesized subpattern.' Where can I read about subpatterns? An official place that is not like w3schools.com.
/**
* Gets a chunk of page content
* @param String the tag wrapping the block ( <!-- START tag --> block <!-- END tag --> )
* @return String the block of content
*/
public function getBlock( $tag )
{
preg_match ('#<!-- START '. $tag . ' -->(.+?)<!-- END '. $tag . ' -->#si', $this->content, $tor);
$tor = str_replace ('<!-- START '. $tag . ' -->', "", $tor[0]);
$tor = str_replace ('<!-- END ' . $tag . ' -->', "", $tor);
return $tor;
}
Any explanations along with links would be helpful!
Thanks!
Upvotes: 0
Views: 1287
Reputation: 26380
Here's the PHP manual on subpatterns: http://php.net/manual/en/regexp.reference.subpatterns.php
Subpatterns let you do a few things. When the pattern matches, you get the value of the whole match, and also the value of each subpattern. In the case of a very simple regex like this:
Hi, my name is (\w*)\.
With input like this:
Hi, my name is Freddie.
Your match results are an array containing both Hi, my name is Freddie.
and Freddie
.
The subpattern also helps you define the regex. If we change the previous example...
Hi, my name is (Fred|Shaggy)\.
Your regex will only match that sentence if the name given is Freddie or Shaggy. You can load up other all sorts of patterns in there to match. Read up in at the link I provided, it's way to much to explain (and they do it better than I can).
Final note - sometimes you want to capture the subpattern result; sometimes you just want to use it to match the overall pattern. Sometimes you want both.
Upvotes: 1
Reputation: 7880
You can see all of the matches by something something like:
print_r($matches);
You can learn more about capturing groups in PHP here at the regular-expressions.info site.
Upvotes: 3