工作中遇到的正则,作为笔记简单记录一下,不定时更新。
匹配常见的url,包括ip形式,端口,以及常见的字符串,如果没有匹配成功协议,默认添加http://
js端
function isURL (str_url) {
var strRegex = ‘((https|http)://)?‘
+ ‘(‘
+ ‘([0-9]{1,3}.){3}[0-9]{1,3}‘ // IP形式的URL- 199.194.52.184
+ ‘|‘ // 允许IP和DOMAIN(域名)
+ ‘([a-zA-Z0-9_!~*\‘()-]+\\.)*‘ // 域名- www.
+ ‘([a-zA-Z0-9-]{0,61})?[a-zA-Z0-9]\\.‘ // 二级域名
+ ‘[a-z]{2,6}‘ // first level domain- .com or .museum
+ ‘)‘
+ ‘(:[0-9]{1,4})?‘ // 端口- :80
+ ‘([/a-zA-Z0-9_!~*\‘()\\.;?:@&=+^$,%#-]+)?‘;
var re=new RegExp(strRegex,"i");
res = str_url.match(re);
if(res[1] === undefined && typeof(res[1])===‘undefined‘){
ret = str_url.replace(re,"<a href=‘http://$&‘ target=‘_blank‘>$&</a>");
}else{
ret = str_url.replace(re,"<a href=‘$&‘ target=‘_blank‘>$&</a>");
}
// ret = str_url.replace(re,"<a href=‘$&‘ target=‘_blank‘>$&</a>");
return ret;
}
php端:
public function isURL($str){
$pattern = ‘/((https|http):\/\/)?‘
. ‘(‘
. ‘([0-9]{1,3}.){3}[0-9]{1,3}‘ // IP形式的URL- 199.194.52.184
. ‘|‘ // 允许IP和DOMAIN(域名)
. ‘([a-zA-Z0-9_!~*\‘()-]+.)*‘ // 域名- www.
. ‘([a-zA-Z0-9-]{0,61})?[a-zA-Z0-9].‘ // 二级域名
. ‘[a-z]{2,6}‘ // first level domain- .com or .museum
. ‘)‘
. ‘(:[0-9]{1,4})?‘ // 端口- :80
. ‘([\/a-zA-Z0-9_!~*\‘().;?:@&=+^$,%#-]+)?/i‘;
preg_match($pattern,$str,$matches);
if(empty($matches[1])){
$replace = ‘<a href="http://$0" target="_blank">$0</a>‘;
}else{
$replace = ‘<a href="$0" target="_blank">$0</a>‘;
}
// $replace = ‘<a href="$0" target="_blank">$0</a>‘;
$res = preg_replace($pattern, $replace, $str);
return $res;
}
原文:http://www.cnblogs.com/fanfan259/p/5002468.html