簡體   English   中英

PHP刪除指向特定網站的鏈接但保留文本

[英]PHP remove links to specific website but keep text

例如, <a href="http://msdn.microsoft.com/art029nr/">remove links to here but keep text</a> but <a href="http://herpyderp.com">leave all other links alone</a>

我一直試圖用preg_replace來解決這個問題。 我在這里搜索並找到了解決問題的答案。

PHP的答案:從文本中刪除特定域的所有超鏈接會刪除指向特定URL的鏈接,但也會刪除文本。

http://php-opensource-help.blogspot.ie/2010/10/how-to-remove-hyperlink-from-string.html上的網站從字符串中刪除了一個超鏈接,但我似乎無法修改模式所以它只適用於特定的網站。

$html = '...I can haz HTML?...';
$whitelist = array('herpyderp.com', 'google.com');

$dom = new DomDocument();
$dom->loadHtml($html);    
$links = $dom->getELementsByTagName('a');

foreach($links as $link){
  $host = parse_url($link->getAttribute('href'), PHP_URL_HOST);

  if($host && !in_array($host, $whitelist)){    

    // create a text node with the contents of the blacklisted link
    $text = new DomText($link->nodeValue);

    // insert it before the link
    $link->parentNode->insertBefore($text, $link);

    // and remove the link
    $link->parentNode->removeChild($link);
  }  

}

// remove wrapping tags added by the parser
$dom->removeChild($dom->firstChild);            
$dom->replaceChild($dom->firstChild->firstChild->firstChild, $dom->firstChild);

$html = $dom->saveHtml();

對於那些因為性能原因而害怕使用DomDocument而不是preg_replace的人,我在這個和Q中鏈接的代碼之間進行了快速測試(完全刪除鏈接的代碼)=> DomDocument只慢了~4倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM