G.ManJi
G.ManJi

Reputation: 23

Is this a bug of php? How would you 'patch' it?

I'm dealing with this simple script in php :

$a = array('la','co');
foreach ($a as $unboldeda){
    $boldeda[] = '<b style="color: teal;">'.$unboldeda.'</b>';
}
$c = 'land of copper';
echo '<a href="#">'.str_replace($a, $boldeda, $d=$c).'</a>';

It should result into land of copper

but it results into:

color: teal;">land of copper

bacause str_replace() not only replaces the value of $d, but of $c as well, hence in the second iteration $c will also contain html tags. In my view this doesn't make much sense for a programming language. How would you work around this?

Upvotes: 0

Views: 47

Answers (2)

u_mulder
u_mulder

Reputation: 54841

Solution with strtr:

$a = array('la','co');
foreach ($a as $unboldeda){
    $boldeda[$unboldeda] = '<b style="color: teal;">'.$unboldeda.'</b>';
}
$c = 'land of copper';
echo '<a href="#">'.strtr($c, $boldeda).'</a>';

Explanation:

your line

echo '<a href="#">'.str_replace($a, $boldeda, $d=$c).'</a>';

has nothing to do with $d or $c. str_replace changes items from $a to $boldeda in a value, which is a result of operation $d=$c. Result ot this assignment is string land of copper, your $d and $c are both untouched. You can check this by outputting them.

Going further, on a str_replace manpage you will see that it has Replacement order gotcha which tells you that:

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

So, str_replace first replaces la with tag, which has color in it, and second str_replace replaces co with a new substitution. Unfortunately, word color has co too, so, str_replace replaces it too, because it does not "remember" what has been already replaced, and what not.

Upvotes: 3

Ed Heal
Ed Heal

Reputation: 60007

What do you think this part does

$d=$c

It assigns $d to the value of $c and then returns that value.

Just do one thing at a time

Upvotes: 0

Related Questions