preg_replace() eating matched strings
- From: MangroveRoot <zcukpkn02@xxxxxxxxxxxxxx>
- Date: Fri, 15 Feb 2008 00:05:06 GMT
I'm trying to use preg_replace to insert a newline
before each of a set of pattern strings found in a subject string.
(For the sake of discussion, I'm not using an array in this example.)
It each case, it inserts the newline where expected,
but "eats" the substring that triggered the match.
Here's the code:
========
$foo= "Select this or that or Frick and Frack or ECKS and WHY and ZEE.";
echo "\$foo='${foo}'\n";
$foo= preg_replace( "/and/", "\n\${1}", $foo );
$foo= preg_replace( "/but/", "\n\${1}", $foo );
$foo= preg_replace( "/or/", "\n\${1}", $foo );
echo "\$foo='${foo}'\n";
--------
And here is the output:
====
$foo='Select this or that or Frick and Frack or ECKS and WHY and ZEE.'
$foo='Select this
that
Frick
Frack
ECKS
WHY
ZEE.'
----
I have tried:
o leaving out the braces in "\${1}";
o leaving out the "\" (put there to "escape" the dollar sign);
o using "\\1" instead of "${1}" or "\${1}";
and several other variations, most of which worked even worse.
Yes, I used 'hexdump' to be sure that the pattern words were not getting
hidden somehow by the newlines.
Ideas?
.
- Follow-Ups:
- Re: preg_replace() eating matched strings
- From: Janwillem Borleffs
- Re: preg_replace() eating matched strings