Choosing Greedy or Nongreedy Matches

You want your pattern to match the smallest possible string instead of the largest.

By definition, all regular expression quantifiers in PHP are greedy.Greedy matching is also known as maximal and non-greedy matching can be called minimal matching, because these methods match either the maximum or minimum number of characters possible.

Place ? after a quantifier to alter that portion of the pattern.

Or use the U pattern-modifer ending to invert all quantifiers from greedy ("match asmany characters as possible") to non-greedy ("match as few characters as possible").

<html>
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$html = "I really <em>enjoy</em> working with <em>you</em>.";

// <em>.+</em> matches "<em>, one or more characters,</em>
//A greedy regular expression finds one match
$matchcount = preg_match_all('@<em>.+</em>@', $html, $matches);
echo "Greedy count: ", $matchcount, "<br />";

//A non-greedy finds a pair of matches.
$matchcount = preg_match_all('@<em>.+?</em>@', $html, $matches);
echo "First non-greedy count: ", $matchcount, "<br />";
//Non-greedy
$matchcount = preg_match_all('@<em>.+</em>@U', $html, $matches);
echo "Second non-greedy count: ", $matchcount, "<br />";
?>
</p>
</body>
</html>

View the effect


Regular Expressions | Introduction | Matching a Pattern | Metacharacters | Quantifiers | Character Classes | Pattern Modifiers | Matching and Replacing Patterns | Splitting Strings | Finding Elements of an Array | Finding the nth Occurence of a Match | Choosing Greedy or Nongreedy matches
© 2008: Hann So
email: hso@voyager.deanza.edu