最近看到大家都在研究怎么把文中的URL鏈接轉(zhuǎn)換JAVASCRIPT來編寫,我也看了很多,在這里我給大家總結(jié)一下,文本中的URL地址轉(zhuǎn)為可點(diǎn)擊鏈接的JavaScript、PHP來自定義函數(shù)
很久沒有寫文章了,這幾天在寫一個(gè)小程序的時(shí)候,需要用到正則表達(dá)式匹配用戶輸入文本中的URL地址,然后將URL地址替換成可以點(diǎn)擊的鏈接。URL地址的匹配,我想這應(yīng)該是大家在做驗(yàn)證處理中常會(huì)用到的,這里就把我整合的一個(gè)比較完整的表達(dá)式給出來:文本中的URL地址轉(zhuǎn)為可點(diǎn)擊鏈接的JavaScript、PHP來自定義函數(shù)
這個(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:
JavaScrit 版本
PHP版
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;
}
新聞熱點(diǎn)
疑難解答
圖片精選