strip_tags和html_entity_decode组合不像预期的那样工作

4

我已经在昨天开始解决这个问题,但是很遗憾一直没有成功(不过我找到了一种折中的方法)。经过一些研究和重新阅读文档后,我仍然有点困惑。

假设现在有一个丑陋的字符串,其中特殊字符已经被正确地HTML编码,像这样:

$exampleString = '<div id="dynamic2"> <div
id="iStoreProductLongDescription" class="iStoreBox">
<div class="iStoreBoxWrapper"> <div 
class="iStoreBoxContent"> <p style="text-
align:justify;"> </p> <p style="text-
align:justify;"><span style="font-
size:large;"><span> Just a bunch of text here, at 
the end. yedyedyed';

现在我想将这个字符串输出为一个简单干净的字符串,所以首先需要将其转换为HTML标记,然后去掉标记。因此,我想以下链应该可以工作:

$result = strip_tags(htmlspecialchars_decode($exampleString));

但实际上并不是这样,网页源代码中的echo $result输出结果为:

<div id="dynamic2"> <div id="iStoreProductLongDescription" class="iStoreBox"> <div class="iStoreBoxWrapper"> <div class="iStoreBoxContent"> <p style="text-align:justify;"> </p> <p style="text-align:justify;"><span style="font-size:large;"><span> Just a bunch o text here, at the end. yedyedyed

在用户输出中,HTML标签是可见的且保持不变。但是,当我做类似于这样的事情时:
$result = strip_tags(html_entity_decode(htmlspecialchars_decode($exampleString)));

如果一切顺利,输出所需字符串到用户界面和网页源代码的方法都是正确的:

在这里只是一堆文本,最后。yedyedyed

问题在于 - 为什么不会呢?

strip_tags(htmlspecialchars_decode($exampleString));

能够按照预期工作吗?非常感谢任何见解。

谢谢

2个回答

3
如果您仔细观察,会发现您有 &amp;lt; 而不是 &lt;。所以,您首先需要使用 htmlspecialchars_decode&amp;lt; 转换为 &lt;,这肯定是一个特殊实体,可以通过第二次运行 htmlspecialchars_decode(或 html_entity_decode)进行解码为 <,但不能使用 strip_tags 去除。

2

试着像这样做:

$exampleString = '&amp;lt;div id="dynamic2"&amp;gt; &amp;lt;div
id="iStoreProductLongDescription" class="iStoreBox"&amp;gt;
&amp;lt;div class="iStoreBoxWrapper"&amp;gt; &amp;lt;div 
class="iStoreBoxContent"&amp;gt; &amp;lt;p style="text-
align:justify;"&amp;gt; &amp;lt;/p&amp;gt; &amp;lt;p style="text-
align:justify;"&amp;gt;&amp;lt;span style="font-
size:large;"&amp;gt;&amp;lt;span&amp;gt; Just a bunch of text here, at 
the end. yedyedyed';

$result = htmlspecialchars_decode($exampleString); // this will decode the entities
echo $result;

结果应为:

<div id="dynamic2"> <div
id="iStoreProductLongDescription" class="iStoreBox">
<div class="iStoreBoxWrapper"> <div 
class="iStoreBoxContent"> <p style="text-
align:justify;"> </p> <p style="text-
align:justify;"><span style="font-
size:large;"><span> Just a bunch of text here, at 
the end. yedyedyed

在 html_entity_decode() 之后:

$result = html_entity_decode($result); // this will print with HTML
echo $result;

结果应该是(带有html标签):


 Just a bunch of text here, at 
the end. yedyedyed

经过strip_tags()处理后:

$result = strip_tags($result); // this will strip your html tags
$echo $result;

Result Should be (without html tags):

 Just a bunch of text here, at 
the end. yedyedyed

@u_mulder:是的,我明白了,所以我已经分享了解释。 - devpro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接