php preg_match – greedy and lazy regex examples

Php preg_match (preg_replace) can have greedy (default) or lazy regular expressions. Lazy match is done as soon as a valid match is found. Greedy match tries to match the largest possible string. Here are some examples:
php-regex-greedy-lazy

preg_match with star – greedy match

Pattern .* will do the greedy match.

<?php
if (preg_match('/<div.*>/', "<div class=foo></div>", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
<div class=foo></div> (at offset 0)
Env: PHP version 5.5.9 (Linux)

preg_match with star – lazy match

Pattern .*? will do the lazy match. We append question mark after star.

<?php
if (preg_match('/<div.*?>/', "<div class=foo></div>", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
<div class=foo> (at offset 0)
Env: PHP version 5.5.9 (Linux)

preg_match with plus – greedy match

Pattern +* will do the greedy match.

<?php
if (preg_match('#^/.+/#', "/aa/bb/cc/", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
/aa/bb/cc/ (at offset 0)
Env: PHP version 5.5.9 (Linux)

preg_match with plus – lazy match

Pattern .+? will do the lazy match. We append question mark after plus.

<?php
if (preg_match('#^/.+?/#', "/aa/bb/cc/", $matches, PREG_OFFSET_CAPTURE)) {
  echo "matched string:\n{$matches[0][0]} (at offset {$matches[0][1]})\n";
} else {
  echo "No match\n";
}
?>
matched string:
/aa/ (at offset 0)
Env: PHP version 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments