这几天在写一个小程序的时候,需要用到正则表达式匹配用户输入文本中的URL地址,然后将URL地址替换成可以点击的链接。URL地址的匹配,我想这应该是大家在做验证处理中常会用到的,这里就把我整合的一个比较完整的表达式给出来:
复制代码 代码如下:
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;
}
您可能感兴趣的文章:
- PHP实现使用优酷土豆视频地址获取swf播放器分享地址
- 解析获取优酷视频真实下载地址的PHP源代码
- php利用腾讯ip分享计划获取地理位置示例分享
- PHP采集腾讯微博的实现代码
- 腾讯QQ php程序员面试题目整理
- php实现把url转换迅雷thunder资源下载地址的方法
- PHP中IP地址与整型数字互相转换详解
- PHP转换IP地址到真实地址的方法详解
- php获取当前页面完整URL地址
- php将url地址转化为完整的a标签链接代码(php为url地址添加a标签)
- PHP实现将优酷土豆腾讯视频html地址转换成flash swf地址的方法