把文本中的URL地址转换为可点击链接的JavaScript、PHP自定义函数_javascript技巧
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;
这个表达式可以匹配 http,https,ftp,ftps以及IP地址的URL地址。还算是URL地址匹配计较完善的。利用这个表达式我写了两个小函数,将用户留言的URL地址替换成可点击的链接,没有什么太难的,就是利用JavaScript 的 replace() 函数来实现替换 URL 为 link:
JavaScript版:
/**
* JavaScrit 版本
* 将URL地址转化为完整的A标签链接代码
*/
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版:
/**
* PHP 版本 在 Silva 代码的基础上修改的
* 将URL地址转化为完整的A标签链接代码
*/
/** =============================================
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;
}
上一篇: mac 电脑的PHP开发环境配置