echo preg_replace('/:*$/isD', ':', ':blue:');
A fairly simple PHP regex, which is designed to capture as many colons at the end of a string as possible (there may not be any at all) and replace it with just one. Or at least that's what I set out to do.
Here's the output:
:blue::
I expected, since preg_replace
is greedy, that the colon at the end of the string would be captured, and thus I would get
:blue:
instead.
Oddly, using similar code to check for colons at the beginning of a string (i.e. /^(:)*/isD
) works. I'm guessing this has something to do with the fact that regexes search from left to right, so in the non-working end of string example, it's finding only the end of the string, whereas in the working front of string example, it's already found the beginning of the string.
That said, what I can do to make preg_replace
capture all of the ending colons?
echo preg_replace('/:+$/isD', ':', ':blue:');
just replace the *
(means zero or more) by a +
(means one or more).
The *
matches at first all colons till the end and then the empty string, so there are two matches.
Update
To ensure exactly one colon at the end, you can use this:
echo preg_replace('/^(.*?):*$/isD', '$1:', ':blue');
Try replacing the *
with +
so that the empty string is not matched:
echo preg_replace('/:+$/isD', ':', ':blue:');
yields
:blue:
Update
Consider using a variant of trim
, that makes it a little more "light-weight":
echo rtrim(":blue:::::", ":") . ":";
This will remove all the :
from the end and add one :
, as you desired.