为什么包含HTML实体的字符串在通过htmlspecialchars()运行后不显示字符?


Why does a string that contains HTML entity not displaying character after being ran through htmlspecialchars()

我有一个字符串的文本是从SQL拉出来,然后通过PHP strip_tags和htmlspecialchars运行,因为我需要删除所有的HTML格式,我的用户可能会尝试添加。它然后显示在一个文本区以及一个不可编辑的div。,<)这就是我想要的。至于div,这是文本区域内容的预览,我希望它显示实际字符(例如。,& lt;)。因此,我需要div将任何特殊字符转换为html实体,但我希望当前的html实体显示为字符。

这个文本字符串可以包含很多不同的字符,因为它是餐厅设备的技术文字,所以它不仅仅是&和引号。从根本上说,有足够的理由来列出一个清单并不是一个容易的选择。

这是我在textarea和预览div中运行字符串的函数:

function removeTags($data) {
    $data = strip_tags($data);
    $data = htmlspecialchars($data, ENT_HTML5, 'UTF-8');
    return $data;
}

这是文本区显示的内容:

This unit has the ability to lower food temperature from 160&#176;F to 38&#176;F, with 110 lbs.

不幸的是,预览div显示相同的信息,但我希望预览div显示下面的行,同时仍然删除任何HTML标签以及将任何特殊字符转换为HTML实体:

该设备能够将食物温度从160°F降低到38°F,重量为110磅。

htmlspecialchars()函数将某些字符(如&)转换为它们的HTML实体(如&amp;)。

另外,如果您想转换所有字符,而不仅仅是htmlspecialchars()转换的字符,请使用htmlentities()代替。

然后你可以使用str_replace()函数来显示HTML实体。

例如:

$data = "This unit has the ability to lower food temperature from 160°F to 38°F, with 110 lbs.";
$data = "This unit has the ability to lower food temperature from 160°F to 38°F, with 110 lbs.";
function removeTags($data) {
    $data = strip_tags($data);
    $data = htmlentities($data);
    return $data;
}
echo '<textarea cols="95" rows="6">' . str_replace('&', '&amp;', removeTags($data)) . '</textarea>';
echo '<div>' . removeTags($data) . '</div>';

在文本区中,输出为:

This unit has the ability to lower food temperature from 160&deg;F to 38&deg;F, with 110 lbs.

在div中,输出为:

This unit has the ability to lower food temperature from 160°F to 38°F, with 110 lbs.