note 25415 added to function.preg-replace
| From: | jared at cybaeus dot spam dot com | Date: | Mon, 23 Sep 2002 09:03:37 +0000 |
| Subject: | note 25415 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-37132@lists.php.net to get a copy of this message | ||
Regarding the last note on replacement strings containing numbers -- which in turn get seen as part
of the replacement pattern when substituting like so: \\1$replacement.
The date example fix may work, but I'm doing many replacements on a database so I wanted to get
it right with one line if possible. My line of text used some pipe (|) delimiters to split up some
numbers. Rather than exploding them, updating the changes and finally rebuilding the line, I used
something like this:
$text = '1|2|3|4|5|6|7|8|9|10';
$pattern = '/(.*)((\|.*){2})((\|.*){3})/U';
$replacement = '|100|100|';
echo preg_replace($pattern,"\\1\\2$replacement",$text);
The key for my needs was making the replacement text/numbers surrounded by the pipe delimiters.
This way the first character is not treated as part of the n'th match (i.e. \\1$replacement
becomes \\1|100|100| instead of \\1100|100).
By using the [U]ngreedy modifier and making the first matchable sub-pattern a (.*), the second
sub-pattern actually matches {n+1} items between the pipe delimiters. Since it's actually 2
pattern matches put together, the replacement substitution is \\1\\2 instead of only \\1 ...
assuming you want to keep the first portion of the original text as you found it.
From that point in the replacement pattern (after \\1\\2) your replacement string is inserted. Your
sub-pattern match count ({3} in the example for 3 pipes) has to pair up with the number of
pipes/elements you're sticking in as a replacement. This match in the pattern makes for the
3rd sub-pattern match or \\3 BTW.
The remainder of the original string is returned as-is since it doesn't match anything after
the last or 3rd sub-pattern (not matched, not replaced). Adding another (.*) sub-pattern to the end
of the pattern (creating a \\4) would zap the remainder of the string, ending it after your inserted
text.
This worked for my case but might not if you need the replacement right at the beginning of the
original string. With a little tweaking and TLC, it should work for most cases where delimiters are
used. If anyone knows or can suggest a better way to work around the "\\1$numbers"
problem, don't hesitate to holler.
Getting a pattern to match as you expected is always a great way to spend the weekend ;)
Enjoy!
--
http://www.php.net/manual/en/function.preg-replace.php
http://master.php.net/manage/user-notes.php?action=edit+25415
http://master.php.net/manage/user-notes.php?action=delete+25415
http://master.php.net/manage/user-notes.php?action=reject+25415