Re: str_replace problem

From: Date: Wed, 20 Oct 2004 10:24:11 +0000
Subject: Re: str_replace problem
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-199862@lists.php.net to get a copy of this message
On Wed, 20 Oct 2004 01:02:12 -0500, Chris Ditty <cditty@gmail.com> wrote: > Hi all. I'm trying to do a little code snippets page for a site I am > working on. I figured it would be simple enough. I would do a > str_replace and replace the various html codes with the ascii > eqivulant. Unfortunately, it is not working as expected. Can anyone > help with this? > > This is what I am using. > $snippetCode = str_replace("\n", "<br>", > $snippet['snippetCode']); > $snippetCode = str_replace("<", "&gt;", $snippetCode); > $snippetCode = str_replace(">", "&lt;", $snippetCode); > $snippetCode = str_replace("&", "&amp;", $snippetCode); > > This is what is in $snippet['snippetCode']. > ?><pre><? print_r($ArrayName); ?></pre><? > > This is what is showing on the web page. > ?&lt;&gt;pre&lt;&gt;? print_r($ArrayName); > ?&lt;&gt;/pre&lt;&gt;? Ok, first off there are builtin functions to do this kind of thing: http://www.php.net/htmlspecialchars http://www.php.net/nl2br Secondly, think about what your code is doing, and the order that it's doing the replacements. The first thing you're doing is replacing the newlines with <br> tags. The second and third things you're doing will disable all the tags including the <br> tags you've just inserted, by replacing '<' with &lt; and '> with &gt html entities; The fourth thing you're doing is disabling the html entities by replacing '&' with &amp; including the entities you've just inserted as steps two and three. -robin

« previous php.general (#199862) next »