php ereg_replace 正则智能去除超链接

有时候我们需要用php删除文章中的超链接,可以用ereg_replace(“<a [^>]*>.+<\/a>”, “”, $content)删除全部超链接,但是这样做会误删掉锚文本,造成文章阅读障碍;
也可以ereg_replace(“<a [^>]*>|<\/a>”, “”, $content),这样可以删掉<a>标签而保留锚文本,但是这么做就会把纯文本链接也保留下来。
那么有没有既能删除超链接又能保留文本信息呢?当然有~
$content = ereg_replace(“<a [^>]*>http:\/\/([^>]*)<\/a>”, “”, $content);//删除所有锚文本带http信息的链接,这一步一般能消灭掉80%的超链接;
$content = ereg_replace(“<a [^>]*>([a-z0-9-]*)+\.([a-z0-9-]*)<\/a>”, “”, $content);//如果有的超链接不带http,上一条就失效了,但是可以通过这一步来匹配。其格式就是***.com ***.cn等格式的链接;
$content = ereg_replace(“<a [^>]*>([a-z0-9-]*)+\.([a-z0-9-]*)+\.([a-z0-9-]*)<\/a>”, “”, $content);//同上,www.***.com gold.***.cn等
$content = ereg_replace(“<a [^>]*>|<\/a>”, “”, $content);//删掉<a>标签而保留锚文本了

通过以上三部过滤,基本可以剔除不必要的链接而保留文本文字了。

当然这样也不全面,如果原文章中只有纯文本的链接,这方法就不适用了,但是可以这样做:
$content = ereg_replace(“http:\/\/([^>]*)+\.(com)”, “”, $content);
$content = ereg_replace(“([a-z0-9-]*)+\.([a-z0-9-]*)+\.([a-z0-9-]*)”, “”, $content);
以上方法理论上虽然可行,但是实际上及易误删内容,所以不推荐。

实例:

<?php
echo “<meta charset=\”UTF-8\”>”;
$content=’海贼王同人小说:《<a href=”http://www.cnonepiece.com/booklist.php?name=hzwzhzw” target=”_blank”>海贼王之海贼王</a>》在线阅读《<a href=”http://www.cnonepiece.com/booklist.php?name=hzwzhzw” target=”_blank”>http://yin.zhaicool.net/</a>》在线阅读《<a href=”http://www.cnonepiece.com/booklist.php?name=hzwzhzw” target=”_blank”>http://web.zhaicool.net</a>》’;
$content = preg_replace(‘/<p.+?>/i’, ‘<p>’, $content);
$content = ereg_replace(“<a [^>]*>http:\/\/([^>]*)<\/a>”, “”, $content);
$content = ereg_replace(“<a [^>]*>([a-z0-9-]*)+\.([a-z0-9-]*)<\/a>”, “”, $content);
$content = ereg_replace(“<a [^>]*>([a-z0-9-]*)+\.([a-z0-9-]*)+\.([a-z0-9-]*)<\/a>”, “”, $content);
$content = ereg_replace(“<a [^>]*>|<\/a>”, “”, $content);
echo $content;//海贼王同人小说:《海贼王之海贼王》在线阅读《》在线阅读《》
?>

未经允许不得转载:前端撸码笔记 » php ereg_replace 正则智能去除超链接

上一篇:

下一篇: