2010-09-23 25 views
12

我有下面的代碼:爲什麼strip_tags不能在PHP中工作?

<?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>今年夏天,格陵蘭西北部的彼得曼冰川(Petermann Glacier)產下了一大塊冰塊,面積近100平方英里(260平方公里),是曼哈頓四倍大小的」

<p>標籤是我在這個應用程序中的一個問題,然而strip_tags絕對拒絕刪除它,我找不到原因。其實,我放棄了用strip_tags並試圖做的preg_replace,而不是用正則表達式/ < | *> /(\ n。):

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

但是,這並沒有任何工作!輸出時如何從這個字符串去掉所有的HTML標籤(匹配或不匹配)?

+4

你是否確定它不是'&lt; p >'那是在那裏? – Wrikken 2010-09-23 17:25:14

+0

我已經在你的字符串上測試過strip_tags(),它在這裏工作。 – Evert 2010-09-23 17:45:13

回答

47

嘗試:

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

一直在尋找這個年齡!謝謝。 – hohner 2012-10-16 13:01:16

+0

爲我工作,謝謝! – 2014-01-05 20:38:21

+0

感謝你的這一點,它解決了我試圖治癒好幾個小時的問題。 – Steve 2016-04-15 21:45:06

6

很好奇的是帶標籤不起作用....

也許你的「<p>」是htmlentity編碼?像「& lt; p & gt;」 (看看網頁的源代碼)

otehrwise這將替換所有的標籤,也htmlentity編碼的,但它幾乎是顯而易見的,這對標記只是htmlentity編碼,以便嘗試第一...

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);