views:

69

answers:

2

I am having trouble preserving an ampersand in a code example on my blog, because all HTML entities start with &.

Any tips?

For example:

<pre>
<code>
<?php 
$pageTitle = str_replace('&', ' &amp;', $page->attributes()->title);
?>
</code>
</pre>

Renders as:

<?php 
$pageTitle = str_replace('&', '&', $page->attributes()->title);
?>
+3  A: 

I'm not sure if it's the best option, but one workaround is to double-escape it:

str_replace('&', ' &amp;amp;', $page->attributes()->title);

This way, the first &amp; shows up as a literal ampersand, then the remaining amp; shows up as literal text.

Mark Rushakoff
In fact, that is how Stack Overflow rendered it in the question.
Daniel Vassallo
hahaaaaa... that is so obvious and yet I didn't think of it. Thanks!
Marcy Sutton
A: 

You need to encode the string with htmlentities(). For example,

<pre>
<code>
<?php
echo htmlentities("$pageTitle = str_replace('&', ' &amp;', $page->attributes()->title)");
?>
</code>
</pre>
ZZ Coder
this would work too.
Marcy Sutton