为什么 PHP 中的 strip_tags 函数无效?

25

我有以下代码:

<?php echo strip_tags($firstArticle->introtext); ?>

$firstArticle 是一个 stdClass 对象:

object(stdClass)[422]
  public 'link' => string '/maps101/index.php?option=com_content&view=article&id=57:greenlands-newest-iceberg&catid=11:geography-in-the-news' (length=125)
  public 'text' => string 'GREENLAND'S NEWEST ICEBERG' (length=26)
  public 'introtext' => string '<p>A giant chunk of ice calved off the Petermann Glacier on

    the northwest side of Greenland this summer. At nearly 100 square miles (260

    sq. km) in size, four times the size of Manhattan, th' (length=206)
  public 'date' => 
    object(JDate)[423]
      public '_date' => int 1284130800
      public '_offset' => int 0
      public '_errors' => 
        array
          empty
你可以看到$firstArticle->introtext引用的字符串是:
"<p>A giant chunk of ice calved off the Petermann Glacier on the northwest side of Greenland this summer. At nearly 100 square miles (260 sq. km) in size, four times the size of Manhattan, th"
在这个应用程序中,<p>标签对我造成了困扰,但是strip_tags绝对拒绝删除它,我无法弄清楚为什么。我实际上放弃了strip_tags,并尝试使用正则表达式 /<(.|\n)*?>/ 进行preg_replace替换:
preg_replace('/<(.|\n)*?>/', '', $firstArticle->introtext);

但是那也不起作用!当我输出它时,我该如何从这个字符串中剥离所有HTML标记(匹配或不匹配)?


4
你非常确定那里面不是<p>吗? - Wrikken
我已经在你的字符串上测试了strip_tags()函数,它可以正常工作。 - Evert
3个回答

87

尝试:

<?php echo strip_tags(html_entity_decode($firstArticle->introtext)); ?>

2
找了好久终于找到了!谢谢。 - hohner
谢谢,这解决了我几个小时一直在尝试解决的问题。 - Steve
请问您能否解释一下为什么添加html_entity_decode可以解决这个问题? - yofisim
3
如果字符串包含编码的HTML实体,它实际上不包含任何标签,因此这种行为是可以预料的。如果您在应用程序中使用该字符串以防止XSS注入和类似问题,则应确保重新对其进行编码。 - The Surrican
完美的解决方案。谢谢兄弟。 - NightOwl
@yofisim:就像Surrica所说的那样。如果您想查看内容是否已编码,请尝试使用var_dump($content),如果您得到类似于&lt;p&gt;something&lt;/p&gt;而不是<p>something</p>这样的结果,则应使用html_entity_decode来去除标签。 - Zankar

6
非常好奇strip-tags不起作用....也许你的"<p>"被HTML实体编码了?比如"&lt;p&gt;"(查看页面源代码)
否则,这将取代所有标签,包括HTML实体编码的标签,但几乎可以肯定,此p标签只是HTML实体编码的,所以首先尝试这个...
preg_replace('/(?:<|&lt;).*?(?:>|&gt;)/', '', $firstArticle->introtext);

1
在我的情况下,我应该使用htmlspecialchars_decode($str);。对我来说html_entity_decode($firstArticle->introtext)似乎不起作用。
有时我必须先使用htmlentities
        $txt = htmlentities($txt, null, 'utf-8');   
        $txt = htmlspecialchars_decode($txt);

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