如果不存在锚,则检查字符串并创建链接

时间:2012-08-10 08:21:05

标签: php regex

此函数从字符串创建链接,但问题是,如果我已经有链接,它不起作用,例如:'我是链接',但它适用于'我是一个链接http://www.google.com'。任何想法?

 function checkStringForLinks($string)
{
    /*** make sure there is an http:// on all URLs ***/
    //$string = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$string);

    /*** make all URLs links ***/
    $string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</A>",$string);

    /*** make all emails hot links ***/
    //$string = preg_replace("/([\w-?&;#~=\.\/]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?))/i","<A HREF=\"mailto:$1\">$1</A>",$string);

    return $string;
}

ooops,错误的类型。我的意思是:我不想让它触及\ anchor \ link \ anchor \而只是触及未形成的链接

2 个答案:

答案 0 :(得分:1)

为了使它正确,它不是那么简单,已经有了免费的解决方案。就像这个简单的班级linkify

 $string = 'some text http://www.google.com <a href="http://www.google.com">google.com</a>';Some text http://www.google.com Some text <a href="http://www.google.com">google.com</a>
 echo Util::linkify($string);
 //returns 
 //Some text <a href="http://www.google.com">http://www.google.com</a> Some text <a   href="http://www.google.com">google.com</a>

答案 1 :(得分:0)

$string = preg_replace("/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</A>",$string);

添加\之前:并且您不需要()和$ 1,只需使用$ 0代替