2012-02-01 48 views
0

我想实现一个url匹配算法,该算法检测以http或https开头的每个url。我想出了一个解决方案,但我不知道它是否足以只考虑空间和控制字符使用php-regex的网址检测算法

function func($str){ 
    $url = '/((http|https)[^[:space:][:cntrl:]]+)/i'; 
    $str = nl2br(htmlspecialchars($str)); 
    return preg_replace($url, '<a href="$1" target="_blank">$1</a>', $str); 
} 
+0

谷歌是你的朋友! http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1你应该更频繁地使用它:) – Tom 2012-02-01 03:36:27

+0

重复? [PHP验证/正则表达式的URL](http://stackoverflow.com/questions/206059/php-validation-regex-for-url) – Josh 2012-02-01 03:43:52

+0

可能重复[PHP正则表达式验证URL](http:// stackoverflow。 COM /问题/ 2390275/PHP的正则表达式,用于验证的-A-URL) – 2012-02-02 05:05:05

回答

1

事情是这样的:

 

function url_link($str) { 
    if (preg_match_all("#(^|\s|\()((http(s?)://)|(www\.))(\w+[^\s\)\<]+)#i", $str, $matches)) { 
     $target = " target=\"_blank\" "; 

     for ($i = 0; $i < count($matches['0']); $i++) { 
      $period = ''; 
      if (preg_match("|\.$|", $matches['6'][$i])) { 
       $period = '.'; 
       $matches['6'][$i] = substr($matches['6'][$i], 0, -1); 
      } 

      $str = str_replace($matches['0'][$i], $matches['1'][$i] . '<a href="http' . 
        $matches['4'][$i] . '://' . 
        $matches['5'][$i] . 
        $matches['6'][$i] . '"' . $target . '>http' . 
        $matches['4'][$i] . '://' . 
        $matches['5'][$i] . 
        $matches['6'][$i] . '</a>' . 
        $period, $str); 
     } 
    } 
    return $str; 
} 
 

希望它可以帮助