0

I wanted to implement a url matching algorithm that detects every url which starts with http or https. I come up with a solution but I am not sure whether it is enough to consider only spaces and control characters

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);
}
xiphos_
  • 171
  • 1
  • 1
  • 3
  • Google is your friend! http://regexlib.com/Search.aspx?k=URL&AspxAutoDetectCookieSupport=1 You should use it more often :) – Tom Feb 01 '12 at 03:36
  • Duplicate? [PHP validation/regex for URL](http://stackoverflow.com/questions/206059/php-validation-regex-for-url) – Josh Feb 01 '12 at 03:43
  • possible duplicate of [PHP regex for validating a URL](http://stackoverflow.com/questions/2390275/php-regex-for-validating-a-url) – David W. Feb 02 '12 at 05:05

1 Answers1

1

Something like this:


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

Hope it helps

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162