使用PHP删除网址

时间:2011-04-30 20:31:12

标签: php regex

我只想删除锚标签和实际网址 例如,<a href="http://www.example.com">test www.example.com</a>将成为test

感谢。

3 个答案:

答案 0 :(得分:4)

我经常使用:

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

请记住,strip_tags可以删除字符串中的所有标记,但“白名单”中指定的标记除外。那是你想要的东西,但我也告诉你这是穷举。

编辑:我找到了原始来源,我得到了正则表达式。为了公平起见,我想引用作者:http://bavotasan.com/tutorials/using-php-to-remove-an-html-tag-from-a-string/

答案 1 :(得分:2)

你应该考虑使用PHP的DOM库来完成这项工作。

正则表达式不是HTML解析的正确工具。

以下是一个例子:

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

注意:

  • 在此处使用回归循环非常重要,因为在调用replaceChild时,如果旧节点的名称与新节点的名称不同,则一旦替换它,它将从列表中删除,并且链接不会被替换。
  • 此代码不会从节点内的文本中删除网址,您可以在createTextNode行之前使用$ lnkText上的nico中的preg_replace。使用DOM从html中隔离部件总是更好,然后在这些仅文本部分上使用正则表达式。

答案 2 :(得分:1)

为了补充gd1的答案,这将获得所有网址:

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