Alê Moraes Alê Moraes - 2 years ago 88
PHP Question

Using double quotes on str_replace

I'm trying to use

to change my code:

$changeli = "li id=\"head{$raiz}\" class=\"head\"";
$changeli2 = "li id=\"foot{$raiz}\" class=\"foot\"";

echo $changeli; // result li id="head-all" class="head"
echo $changeli2; // result li id="foot-all" class="foot"

$footer = str_replace($changeli, $changeli2, $footer );

It doesn't work, but when I remove the text up to the double quotes, it works, as follows:

$changeli = "head{$raiz}";
$changeli2 = "foot{$raiz}";

echo $changeli; // result head-all
echo $changeli2; // result foot-all

$footer = str_replace($changeli, $changeli2, $footer );

Can someone help me?

Answer Source

Better yet, try to use ' instead of " for the outer quote so you don't have to escape it at all. And concatenate $raiz with your string. The problem is most likely characters that should be escaped in html.

Try this, this works (see this code exactly here):

$changeli = 'li id="head'.$raiz.'" class="head"';
$changeli2 = 'li id="foot'.$raiz.'" class="foot"';

// value of $raiz is "-all" at this point (for clarity of code)
echo $changeli; // result should be li id="head-all" class="head"
echo $changeli2; // result should be li id="foot-all" class="foot"

$footer = htmlspecialchars_decode(str_replace(htmlspecialchars($changeli), htmlspecialchars($changeli2), htmlspecialchars($footer)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download