2010-09-30 65 views
4

如何刪除鏈接並保留文本?如何從PHP中的內容中刪除鏈接?

text text text. <br><a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a> 

這樣的:

text text text. <br> 

我仍然有一個問題.....

$text = file_get_contents('http://www.example.com/file.php?id=name'); 
echo preg_replace('#<a.*?>.*?</a>#i', '', $text) 

在該URL文本(帶鏈接)...

此代碼不起作用...

什麼'你錯了嗎?

有人可以幫助我嗎?

回答

17

我建議你保持鏈接文本。

strip_tags($text, '<br>'); 

或硬的方式:

preg_replace('#<a.*?>(.*?)</a>#i', '\1', $text) 

如果您不需要保留文本中的鏈接

preg_replace('#<a.*?>.*?</a>#i', '', $text) 
+2

他並沒有說明他想的名字留 – methodin 2010-09-30 13:08:43

+0

謝謝檸多 – Adrian 2010-09-30 13:14:37

+0

preg_replace('#。*? #i','',$ text)幫我 – Adrian 2010-09-30 13:15:27

3

嘗試:

preg_replace('/<a.*?<\/a>/','',"test test testa<br> <a href='http://www.example.com' target='_blank' title='title' style='text-decoration:none;'>name</a>"); 
+1

更好地使用'/ /'忽略標籤,如'','

'等 – Philipp 2017-05-13 20:12:37

4

雖然strip_tags()是能夠進行基本的字符串消毒,不是t傻瓜證明。如果您需要過濾的數據來自用戶,並且特別是將其顯示回給其他用戶,則可能需要查看更全面的HTML清理程序,例如HTML Purifier。這些類型的圖書館可以幫助您避免路上的許多頭痛。

strip_tags()和各種正則表達式方法不能也不會阻止真正想要注入某些東西的用戶。

+0

一個投票的HTML淨化器:) – coolkid 2010-09-30 13:54:03

0

這是我的解決方案:

function removeLink($str){ 
$regex = '/<a (.*)<\/a>/isU'; 
preg_match_all($regex,$str,$result); 
foreach($result[0] as $rs) 
{ 
    $regex = '/<a (.*)>(.*)<\/a>/isU'; 
    $text = preg_replace($regex,'$2',$rs); 
    $str = str_replace($rs,$text,$str); 
} 
return $str;} 

dang tin rao vat

-1

還有一個沒有正則表達式的短期解決方案:

function remove_links($s){ 
    while(TRUE){ 
     @list($pre,$mid) = explode('<a',$s,2); 
     @list($mid,$post) = explode('</a>',$mid,2); 
     $s = $pre.$post; 
     if (is_null($post))return $s; 
    } 
} 
?> 
+1

正則表達式更簡單,更省電,比這樣的字符串操作的while循環更有效。試想一下HTML代碼包含'',那麼這段代碼可能會丟失大量文本... – Philipp 2017-05-13 20:06:05

+0

與您同意。 – dmikam 2017-05-16 23:58:36