perl compatible regex search&replace behaving oddly... bug?
| From: | Alexander Fordyce | Date: | Tue, 18 Jan 2000 10:04:09 +0000 |
| Subject: | perl compatible regex search&replace behaving oddly... bug? | ||
| References: | 1 2 3 4 | Groups: | php.version4 |
| Request: | Send a blank email to php-version4+get-9220@lists.php.net to get a copy of this message | ||
Afternoon, all.
Is this a bug, or am I doing something wrong? (there's definitely something wrong somewhere).
Perl compatible search&replace is not doing what it seems like it should with with multiple \\n references. It will replace one occurrence, but it goes crazy on more than one. I'm trying to use it for simple variable interpolation:
- - - - - - - - - - - - - - -
$var1 = "contents1"; $var2 = "contents2";
$str = "<HTML><BODY>
this is one variable: #var1#,<BR>
and this is another: #var2#.
</BODY></HTML>";
echo preg_replace("/#([^#]+)#/e", "$\\1", $str);
- - output: - -
Parse error: parse error, expecting
T_VARIABLE' or '$'' in /tests/preg_test.html on line 0
this is one variable: contents1,
and this is another: .
- - - - - - - - - - - - - - -
I realize that the parse error occurs because it's not finding anything nice and executable the second time around. Sometimes it produces an ugly binary-looking garbage value for the second variable -- it's a bit unpredictable.
It works fine with multiple non-referenced substitutions: e.g.
$str = preg_replace("/this/", "here", $str)
- - output: - -
here is one variable: #var1#,
and here is another: #var2#.
So is this a bug, or is it just a non-feature? It seems odd to implement this function which has the equivalent of Perl's "/g" flag forcibly turned on and then not allow references to work.
It seems like it should work, as that's the way it's presented in the documentation. However, the example from the manual which is supposed to upper-case html tags produces similar garbage when I copy and paste the code:
- - - - - - - - - - - - - - -
$html_body = "<P>just some <strong>nice</strong> <b>simple</b> text</P>";
print preg_replace("/(<\/?)(\w+)([^>]*>)/e", "'\\1'.strtoupper('\\2').'\\3'", $html_body);
- - output: - -
<P>just some rONG>NIcniceb> TEXT</ simple textó(;
- - - - - - - - - - - - - - -
(Btw, I know there are millions of ways to achieve the same or similar effect, but I'm asking because this is one of the most frequently used constructions in all my Perl programs, and the Perl way is so much simpler and cleaner than anything I've been able to hack together with PHP.)
Thanks much for any insights,
Alex