preg_match_all

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
winsonlee
Forum Commoner
Posts: 76
Joined: Thu Dec 11, 2003 8:49 pm

preg_match_all

Post 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 ?
User avatar
EverLearning
Forum Contributor
Posts: 282
Joined: Sat Feb 23, 2008 3:49 am
Location: Niš, Serbia

Re: preg_match_all

Post 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 :)
winsonlee
Forum Commoner
Posts: 76
Joined: Thu Dec 11, 2003 8:49 pm

Re: preg_match_all

Post by winsonlee »

that works just fine.

thanks
Post Reply