PHP Knowledge Base
Regular Expressions
Greedy versus Lazy Quantifiers
'Greedy' Quanitifer Example
Code
<?php
$regexp = '/<.*>/';
$str = '<p>This is a paragraph with a <a href="https://example.com">link</a>.</p>';
preg_match_all($regexp, $str, $matches);
$total_matches = count($matches[0]);
echo "Total matches = $total_matches";
?>
Output
Total matches = 1
'Lazy' Quanitifer Example
Code
<?php
$regexp = '/<.*?>/';
$str = '<p>This is a paragraph with a <a href="https://example.com">link</a>.</p>';
preg_match_all($regexp, $str, $matches);
$total_matches = count($matches[0]);
echo "Total matches = $total_matches";
?>
Output
Total matches = 4