给文本中的url加超级链接,同时滤过已加过链接的url

/**
 * 给文本中的url加超级链接,同时滤过已有链接的url
 * @param  string $str [description]
 * @return [type]      [description]
 */
function text2links($str='') {
    if($str=='' or !preg_match('/(http|www\.|@)/i', $str)) return $str;
    
    $lines = explode("\n", $str);
    $new_text = '';
    while (list($k,$l) = each($lines)) {
        // replace links:
        $l = preg_replace("/([ \t]|^)www\./i", "\\1http://www.", $l);
        $l = preg_replace("/([ \t]|^)ftp\./i", "\\1ftp://ftp.", $l);
        $l = preg_replace("/([^=\'\"]http:\/\/[^ )!]+)/i","<a href=\"\\1\">\\1</a>", $l);
        $l = preg_replace("/([^=\'\"]https:\/\/[^ )!]+)/i","<a href=\"\\1\">\\1</a>", $l);
        $l = preg_replace("/(ftp:\/\/[^ )!]+)/i","<a href=\"\\1\">\\1</a>", $l);
        $l = preg_replace("/([-a-z0-9_]+(\.[_a-z0-9-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)+))/i","<a href=\"mailto:\\1\">\\1</a>", $l);
        $new_text .= $l."\n";
    }
    return $new_text;
}
$text = "open: http://www.baidu.com/ and <a href='http://www.baidu.com'>hehe</a>";
var_dump(text2links($text));

输出结果:

string(109) "open:<a href=" http://www.baidu.com/"> http://www.baidu.com/</a> and <a href='http://www.baidu.com'>hehe</a>"

 

posted @ 2015-04-26 21:28  科学家会武术  阅读(192)  评论(0编辑  收藏  举报