Home > OS >  preg_replace() with a match followed by a string that start with a number
preg_replace() with a match followed by a string that start with a number

Time:09-26

I am trying to replace a the content of href attribute with another URL

So I use this script

$html = 'data-content="111"';
$var_2 = "222";
$html = preg_replace('/(["\'])111\1/i',"$1$var_2$1",$html);
echo $html  

The output was

data-content=22"

What I was expecting

data-content="222"

The problem is that the compiler look for match $12 because $var_2 start with the number "2"

I tried to edit the code like this but no luck

$html = preg_replace('/(["\'])111\1/i','$1'.$var_2.'$1',$html);

CodePudding user response:

You can work around this issue by using a 2-digit number (in this case 01) for the replacement group:

$html = 'data-content="111"';
$var_2 = "222";
$html = preg_replace('/(["\'])111\1/i', "$01$var_2$1",$html);
echo $html;

Output:

data-content="222"

Demo on 3v4l.org

You can also work around it using the method described in the preg_replace manual page:

When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar \1 notation for your backreference. \11, for example, would confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use ${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.

$html = preg_replace('/(["\'])111\1/i', '${1}' . "$var_2$1",$html);

Note in this case ${1} must be enclosed in single quotes to prevent PHP from attempting to substitute it with the value of the variable $1.

Demo on 3v4l.org

  • Related