亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

把文本中的URL地址轉(zhuǎn)換為可點(diǎn)擊鏈接的JavaScript、PHP自定義函數(shù)

 更新時(shí)間:2014年07月29日 10:21:12   投稿:junjie  
這篇文章主要介紹了把文本中的URL地址轉(zhuǎn)換為可點(diǎn)擊鏈接的JavaScript、PHP自定義函數(shù),需要的朋友可以參考下

這幾天在寫一個(gè)小程序的時(shí)候,需要用到正則表達(dá)式匹配用戶輸入文本中的URL地址,然后將URL地址替換成可以點(diǎn)擊的鏈接。URL地址的匹配,我想這應(yīng)該是大家在做驗(yàn)證處理中常會(huì)用到的,這里就把我整合的一個(gè)比較完整的表達(dá)式給出來:

復(fù)制代碼 代碼如下:

var URL = /(https?:\/\/|ftps?:\/\/)?((\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(:[0-9]+)?|(localhost)(:[0-9]+)?|([\w]+\.)(\S+)(\w{2,4})(:[0-9]+)?)(\/?([\w#!:.?+=&%@!\-\/]+))?/ig;

這個(gè)表達(dá)式可以匹配 http,https,ftp,ftps以及IP地址的URL地址。還算是URL地址匹配計(jì)較完善的。利用這個(gè)表達(dá)式我寫了兩個(gè)小函數(shù),將用戶留言的URL地址替換成可點(diǎn)擊的鏈接,沒有什么太難的,就是利用JavaScript 的 replace() 函數(shù)來實(shí)現(xiàn)替換 URL 為 link:

JavaScript版:

復(fù)制代碼 代碼如下:

/**
 * JavaScrit 版本
 * 將URL地址轉(zhuǎn)化為完整的A標(biāo)簽鏈接代碼
 */
var replaceURLToLink = function (text) {
        text = text.replace(URL, function (url) {
            var urlText = url;
            if (!url.match('^https?:\/\/')) {
                url = 'http://' + url;
            }
            return '' + urlText + '';
        });

        return text;
    };

PHP版:

復(fù)制代碼 代碼如下:

/**
 * PHP 版本 在 Silva 代碼的基礎(chǔ)上修改的
 * 將URL地址轉(zhuǎn)化為完整的A標(biāo)簽鏈接代碼
 */
/** =============================================
 NAME        : replace_URLtolink()
 VERSION     : 1.0
 AUTHOR      : J de Silva
 DESCRIPTION : returns VOID; handles converting
 URLs into clickable links off a string.
 TYPE        : functions
 ============================================= */

function replace_URLtolink($text) {
    // grab anything that looks like a URL...
    $urls = array();
   
    // build the patterns
    $scheme = '(https?\:\/\/|ftps?\:\/\/)?';
    $www = '([\w]+\.)';
    $local = 'localhost';
    $ip = '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})';
    $name = '([\w0-9]+)';
    $tld = '(\w{2,4})';
    $port = '(:[0-9]+)?';
    $the_rest = '(\/?([\w#!:.?+=&%@!\-\/]+))?';
    $pattern = $scheme.'('.$ip.$port.'|'.$www.$name.$tld.$port.'|'.$local.$port.')'.$the_rest;
    $pattern = '/'.$pattern.'/is';
   
    // Get the URLs
    $c = preg_match_all($pattern, $text, $m);
   
    if ($c) {
        $urls = $m[0];
    }
   
    // Replace all the URLs
    if (! empty($urls)) {
        foreach ($urls as $url) {
            $pos = strpos('http\:\/\/', $url);
           
            if (($pos && $pos != 0) || !$pos) {
                $fullurl = 'http://'.$url;
            } else {
                $fullurl = $url;
            }
           
            $link = ''.$url.'';
           
            $text = str_replace($url, $link, $text);
        }
    }
   
    return $text;
}

相關(guān)文章

最新評論