note 70833 deleted from function.preg-replace by colder
| From: | colder@php.net | Date: | Mon, 18 Jun 2007 20:05:31 +0000 |
| Subject: | note 70833 deleted from function.preg-replace by colder | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-127707@lists.php.net to get a copy of this message | ||
Note Submitter: bwooster47 at gmail dot com
----
Tripped over a subtle issue in preg_replace!
Eventually got the right answers from the readers at alt.comp.lang.php!
preg_replace assumes a /g - replace all occurences.
So, when you need a replacement to force a single / character at end of string, i.e, replace 0 or
more / characters with single /, here's what you need:
$t = preg_replace('!/*$!', '/', $s, 1);
Note the all important 1 (limit) at the end. Default is -1, and it seems to force a non-greedy match
for /*$ , so if $s == aa//, the output is still a// with limit -1.
But with 1 as the limit, all values of $s such as aa or aa/ or aa// or aa//// all end up like aa/,
just as needed.
[Not sure why a//// ends up as a// with limit -1...]
So, final story, to make *$ be greedy, use the limit of 1.