开发者

Remove urls using PHP

I'd like to only remove the anchor tags and the actual urls.

For i开发者_如何学Cnstance, <a href="http://www.example.com">test www.example.com</a> would become test.

Thanks.


I often use:

$string = preg_replace("/<a[^>]+>/i", "", $string);

And remember that strip_tags can remove all the tags from a string, except the ones specified in a "white list". That's not what you want, but I tell you also this for exhaustiveness.

EDIT: I found the original source where I got that regex. I want to cite the author, for fairness: http://bavotasan.com/tutorials/using-php-to-remove-an-html-tag-from-a-string/


you should consider using the PHP's DOM library for this job.

Regex is not the right tool for HTML parsing.

Here is an example:

// Create a new DOM Document to hold our webpage structure 
$xml = new DOMDocument(); 

// Load the html's contents into DOM 
$xml->loadHTML($html); 

$links = $xml->getElementsByTagName('a');

//Loop through each <a> tags and replace them by their text content    
for ($i = $links->length - 1; $i >= 0; $i--) {
    $linkNode = $links->item($i);
    $lnkText = $linkNode->textContent;
    $newTxtNode = $xml->createTextNode($lnkText);
    $linkNode->parentNode->replaceChild($newTxtNode, $linkNode);
}

Note:

  • It's important to use a regressive loop here, because when calling replaceChild, if the old node has a different name from the new node, it will be removed from the list once it has been replaced, and some of the links would not be replaced.
  • This code doesn't remove urls from the text inside a node, you can use the preg_replace from nico on $lnkText before the createTextNode line. It's always better to isolate parts from html using DOM, and then use regular expressions on these text only parts.


To complement gd1's answer, this will get all the URLs:

// http(s)://
$txt = preg_replace('|https?://www\.[a-z\.0-9]+|i', '', $txt);
// only www.
$txt = preg_replace('|www\.[a-z\.0-9]+|i', '', $txt);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜