在 PHP 中,将富文本内容转义,可以使用 htmlspecialchars() 函数。此函数将特殊字符转换为 HTML 实体,以便于在 HTML 页面中输出,防止 XSS 攻击。
下面是示例代码:
<?php
// 原始富文本内容
$content = 'Welcome to my blog
Here is some bold and italic text.
';
// 转义后的内容
$escaped_content = htmlspecialchars($content);
// 输出转义后的内容
echo $escaped_content;
?>
输出结果为:
<h1>Welcome to my blog</h1><p>Here is some <b>bold</b> and <i>italic</i> text.</p>
注意,转义过程中会将 `<`, `>`, `&`, `”`, `’` 等字符转换为相应的实体。如果需要保留部分 HTML 标记,可以使用第二个参数 `$flags`,具体用法可以查看 PHP 手册。
另外,在输出转义后的富文本内容到 HTML 页面时,需要使用 `html_entity_decode()` 函数进行反转义,以还原原始内容。
正文完