Reputation: 1592
I have a problem with preg_replace and $1 + variable without a space between $1 and the variable.
I have this code:
$replace_id = 5000;
$search = 1000;
$movies = '[1000,2000,2300,1234]';
$new_movies = preg_replace('#(,|\[)'.$search.'(,|\])#Uis','$1'.$replace_id.'$2',$movies);
echo $new_movies;
The output:
000,2000,2300,1234]
But I want to have this output:
[5000,2000,2300,1234]
When I use the preg_replace with a space between $1 and $replace_id:
$new_movies = preg_replace('#(,|\[)'.$search.'(,|\])#Uis','$1 '.$replace_id.'$2',$movies);
It works perfect, but I need this without a space inside!
Do you have any idea?
Thanks!
Upvotes: 3
Views: 1422
Reputation: 46259
From the documentation:
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.
http://php.net/manual/en/function.preg-replace.php
So I would use '${1}'.$replace_id
Upvotes: 6