开发者

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

开发者 https://www.devze.com 2022-12-28 21:43 出处:网络
I am having trouble preserving an ampersand in a code example on my blog, because all HTML entities start with &.

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 = 开发者_StackOverflowstr_replace('&', '&', $page->attributes()->title);
?>


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消