Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings.
以我有限的知识,可以在 PHP 中通过两种不同的方式轻松完成。像这样:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . htmlspecialchars( $some_code, ENT_QUOTES ) . '</code></pre>';
?>
或者这样:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . str_replace( array('<', '>', '&', '\'', '"'), array('<', '>', '&', ''', '"'), $some_code ) . '</code></pre>';
?>
(这只是为了向您展示我正在尝试做什么,而不是我实际上是如何做的。例如,$some_code
是动态提供的,而不是手动提供的。)
不考虑简单地使用 htmlspecialchars()
比 str_replace()
容易得多,两者之一将是对于我想做的事情有更好的选择吗? (就性能而言。)
更新
好的,我发现这需要更多背景信息。这就是我实际上想做的:
<?php
$some_code = '<a href="#test">Test</a>';
echo '<pre><code>' . str_replace(
// Replace these special characters
array( '<', '>', '&', '\'', '"', '‘', '’', '“', '”', '/', '[', ']' ),
// With the HTML entities below, respectively
array('<', '>', '&', ''', '"', ''', ''', '"', '"', '"', '/', '[', ']'),
$some_code
) . '</code></pre>';
?>
对比:
<?php
$some_code = '<a href="#test">Test</a>';
return '<pre><code>' . str_replace(
array( '‘', '’', '“', '”', '/', '[', ']' ),
array(''', ''', '"', '"', '"', '/', '[', ']'),
htmlspecialchars( $content, ENT_QUOTES )
) . '</code></pre>';
?>
最佳答案
您应该将 &
和 &
移动到每个数组的开头以避免双重转义。之后,我建议仅使用 str_replace
,因为它使您想要做的事情更加明显(对我来说,无论如何 - 嵌套函数调用可能会令人困惑!)但这实际上取决于您。性能差异不会很明显;这么大的字符串会导致其他问题。
关于php - str_replace() 或 htmlspecialchars() 用于转义 <pre> block 中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068239/