Why doesn't strip_tags work in PHP?

亡梦爱人 提交于 2019-12-03 08:52:04

问题


I've got the following code:

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

Where $firstArticle is a stdClass object:

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

You can see that $firstArticle->introtext refers to the 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"

The <p> tag is a problem for me in this application, however strip_tags absolutely refuses to remove it and I can't figure out why. I actually gave up on strip_tags and attempted to do a preg_replace instead with the regex /<(.|\n)*?>/ :

preg_replace('/<(.|\n)*?>/', '', $firstArticle->introtext);

But that didn't work either! How can I strip all HTML tags (matched or not) from this string when I output it?


回答1:


try:

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



回答2:


very curious that strip-tags does not work....

maybe your "<p>" is htmlentity-encoded? like "&lt;p&gt;" (have a look at the page's sourcecode)

otehrwise this will replace all tags, also htmlentity-encoded ones, but it's nearly obvious that this p-tag is simply htmlentity-encoded so try that first...

preg_replace('/(?:<|&lt;).*?(?:>|&gt;)/', '', $firstArticle->introtext);



回答3:


In my case, I should use htmlspecialchars_decode($str);. html_entity_decode($firstArticle->introtext) doesn't seem to work for me.

Sometimes I have to use htmlentities first.

        $txt = htmlentities($txt, null, 'utf-8');   
        $txt = htmlspecialchars_decode($txt);


来源:https://stackoverflow.com/questions/3780888/why-doesnt-strip-tags-work-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!