note 110511 deleted from function.preg-replace by crell
| From: | crell@php.net | Date: | Fri, 01 Jul 2022 19:53:51 +0000 |
| Subject: | note 110511 deleted from function.preg-replace by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218870@lists.php.net to get a copy of this message | ||
Note Submitter: cincodenada at gmail dot dot dot com
----
There seems to be some confusion over how greediness works. For those familiar with Regular
Expressions in other languages, particularly Perl: it works like you would expect, and as
documented. Greedy by default, un-greedy if you follow a quantifier with a question mark.
There is a PHP/PCRE-specific U pattern modifier that flips the greediness, so that quantifiers are
by default un-greedy, and become greedy if you follow the quantifier with a question mark: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
To make things clear, a series of examples:
<?php
$preview = "a bunch of stuff <code>this that</code> and more stuff <code>with
a second code block</code> then extra at the end";
$preview_default = preg_replace('/<code>(.*)<\/code>/is', "<code
class=\"prettyprint\">$1</code>", $preview);
$preview_manually_ungreedy = preg_replace('/<code>(.*?)<\/code>/is',
"<code class=\"prettyprint\">$1</code>", $preview);
$preview_U_default = preg_replace('/<code>(.*)<\/code>/isU', "<code
class=\"prettyprint\">$1</code>", $preview);
$preview_U_manually_greedy = preg_replace('/<code>(.*?)<\/code>/isU',
"<code class=\"prettyprint\">$1</code>", $preview);
echo "Default, no ?: $preview_default\n";
echo "Default, with ?: $preview_manually_ungreedy\n";
echo "U flag, no ?: $preview_U_default\n";
echo "U flag, with ?: $preview_U_manually_greedy\n";
?>
Results in this:
Default, no ?: a bunch of stuff <code class="prettyprint">this that</code> and
more stuff <code>with a second code block</code> then extra at the end
Default, with ?: a bunch of stuff <code class="prettyprint">this that</code>
and more stuff <code class="prettyprint">with a second code block</code> then
extra at the end
U flag, no ?: a bunch of stuff <code class="prettyprint">this that</code> and
more stuff <code class="prettyprint">with a second code block</code> then
extra at the end
U flag, with ?: a bunch of stuff <code class="prettyprint">this that</code>
and more stuff <code>with a second code block</code> then extra at the end
As expected: greedy by default, ? inverts it to ungreedy. With the U flag, un-greedy by default, ?
makes it greedy.