用php-regex检测网址的url

时间:2012-02-01 03:33:17

标签: php regex

我想实现一个网址匹配算法,该算法会检测以http或https开头的每个网址。我想出了一个解决方案,但我不确定是否只考虑空格和控制字符

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);
}

1 个答案:

答案 0 :(得分: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;
}

希望有所帮助