正则表达式将URL转换为链接,而不会弄乱文本中的现有链接 [英] regex to turn URLs into links without messing with existing links in the text

查看:114
本文介绍了正则表达式将URL转换为链接,而不会弄乱文本中的现有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式将一段文本中的URL转换为超链接.我已经设法实现了这一点,但是问题是当文本中已经存在链接时

I am trying to convert URLs in a piece of text into hyperlinks - using regular expressions. I have managed to achieve this but the problem is when there are already existing links in the text

如此

bla bla blah www.google.com bla blah <a href="www.google.com">www.google.com</a>

应该导致

bla bla blah <a href="http://www.google.com">www.google.com</a> bla blah <a href="www.google.com">www.google.com</a> 

不是

bla bla blah <a href="http://www.google.com">www.google.com</a> bla blah <a href="<a href="http://www.google.com">www.google.com</a></a>"><a href="http://www.google.com">www.google.com</a></a>

推荐答案

最后完成它:

function add_url_links($data)
{
        $data = preg_replace_callback('/(<a href=.+?<\/a>)/','guard_url',$data);

        $data = preg_replace_callback('/(http:\/\/.+?)([ \\n\\r])/','link_url',$data);
        $data = preg_replace_callback('/^(http:\/\/.+?)/','link_url',$data);
        $data = preg_replace_callback('/(http:\/\/.+?)$/','link_url',$data);

        $data = preg_replace_callback('/{{([a-zA-Z0-9+=]+?)}}/','unguard_url',$data);

        return $data;
}

function guard_url($arr) { return '{{'.base64_encode($arr[1]).'}}'; }
function unguard_url($arr) { return base64_decode($arr[1]); }
function link_url($arr) { return guard_url(array('','<a href="'.$arr[1].'">'.$arr[1].'</a>')).$arr[2]; }

这篇关于正则表达式将URL转换为链接,而不会弄乱文本中的现有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆