Search code examples
phphtmlwordpressescapingmarkup

How to preserve &amp; in <pre><code>


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);
?>

Solution

  • 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.