Reputation: 31
I want to replace {
by {{}
and }
by {}}
, because, I need to escape those {
& }
with {}
.
if I've as input {blah}
I want my script to output {{}blah{}}
, see?
But it is not working look at what I did
$output = str_replace(array("}", "{"), array("{}}", "{{}"), '{blah}');
But as output I got this : {{}blah{{}}}
instead of {{}blah{}}
Upvotes: 2
Views: 110
Reputation: 1064
PHP iterates the whole string for each array item you put in the $search parameter.
It is in fact replacing '{blah}'
into '{blah{}}'
with your first array item '{'
, and then from that into '{{}blah{{}}}'
because there is another '{'
after the first replacement.
You better off doing this with regular expression, with a single RegExp pattern it will run only once in your input string.
$str = preg_replace('/(\{|\})/', '{\\1}', '{blah}');
Upvotes: 4
Reputation: 173642
That's because the replacement itself contains the string to search for. I would rewrite it with preg_replace_callback
instead:
echo preg_replace_callback('/{|}/', function($match) {
return $match[0] == '{' ? '{{}' : '{}}';
}, '{bla}');
// {{}bla{}}
Upvotes: 2