Page 1 of 1

preg_match_all

Posted: Thu Apr 10, 2008 5:48 am
by winsonlee

Code: Select all

 
$str = "<title>one</title><title>two</title><title>three</title><title>four</title><title>five</title>";
 
preg_match_all("/<title>(.*)<\/title>/i", $str, $matches, PREG_SET_ORDER) ;
foreach ($matches as $val) {
    echo $val[1];
}
 
 
with the following code after echoing i only manage to get "one</title><title>two</title><title>three</title><title>four</title><title>five" as the result.
Since it is preg_match_all, why am i not getting the following result
one
two
three
four
five ?

Re: preg_match_all

Posted: Thu Apr 10, 2008 6:03 am
by EverLearning
Regex patterns are by default greedy, which means that it will match as much as it can, which is why you're getting your result. You need to make your pattern ungreedy(by adding ? sign in the pattern)

Code: Select all

preg_match_all("/<title>(.*?)<\/title>/i", $str, $matches, PREG_SET_ORDER) ;
Here are a couple of links

PCRE pattern syntax
Finer points of PHP regular expressions

Google around a little :)

Re: preg_match_all

Posted: Thu Apr 10, 2008 6:40 am
by winsonlee
that works just fine.

thanks