php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #32404 Bug concerning use of preg_replace
Submitted: 2005-03-21 23:03 UTC Modified: 2005-03-23 12:09 UTC
From: thomas-meyer at uni dot de Assigned:
Status: Not a bug Package: PCRE related
PHP Version: 4.3.10 OS: Windows XP
Private report: No CVE-ID: None
 [2005-03-21 23:03 UTC] thomas-meyer at uni dot de
Description:
------------
There is a problem with PCRE in both PHP-versions (4.3.10 and 5.0.3)

When using preg_replace with:

$b = preg_replace("/(some)thing/", "\\1$replace", $a);

This works fine, as long as $replace does start with any character that is NOT a number.

BUT: if $replace starts with a number (like "1abc") FIRST this string: "\\11abc" will be created.
THEN it will try to replace \\11 by the 11th remembered position instead of replacing \\1 with the 1st one.

This bug could lead to strange/unexpected results and should be fixed soon.

Reproduce code:
---------------
<?php

  $temp = '<input value="test">';
  $a = 123;

  echo "<P>Perl</P>\n";

  $temp1 = preg_replace("/(<[^>]*)test([^>]*>)/Usi", "\\1".$a."\\2", $temp);
  echo $temp1;
  
  echo "<P>POSIX</P>\n";

  $temp1 = eregi_replace("(<[^>]*)test([^>]*>)", "\\1".$a."\\2", $temp);
  echo $temp1;

?>

Expected result:
----------------
<P>Perl</P>
<input value="123">
<P>POSIX</P>
<input value="123">

Actual result:
--------------
<P>Perl</P>
23">
<P>POSIX</P>
<input value="123">

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-03-21 23:27 UTC] sniper@php.net
RTFM:
"..backreference is immediately followed by another number  you cannot use the familiar \\1  notation..
..the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1  as a literal."

This works as you expect:

  echo preg_replace("/(<[^>]*)test([^>]*>)/i", "\${1}{$a}\${2}", $temp);


 [2005-03-23 12:09 UTC] thomas-meyer at uni dot de
@sniper That's no "solution" at all! It's just another hack.

It's just: someone put a description for a bug in a documentation and called it a "feature". This won't make things any better.

And besides: it won't work for older versions of PHP. What means: scripts that now "sometimes" create wrong results will then ALWAYS create no result at all.
[IRONY_ON]Great "solution".[/IRONY_OFF]

It lacks logic! The same code works for POSIX, often enough it works for PCRE but SOMETIMES fails because of this "feature".

Bug or feature - I don't care! It should be fixed.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 14:01:29 2024 UTC