|
最近在写用php把url 自动加链接的功能,例如 www.baidu.com
加www.baidu.com;
由于本人正则不是很好就上网搜了一下,发现很多都是如下:
自动给 URL添加链接
Php代码
===========
注意!但是本人的环境是php5.3 eregi_replace 就报错……
Deprecated: Function eregi_replace() is deprecated in
所以我就用preg_match 来替换google 之,综合一下网上的写出
$search = array('|(http://[a-z0-9;&#@=_~%\?\/\.\,\+\-]+)|', '|(https://[a-z0-9;&#@=_~%\?\/\.\,\+\-]+)|', '|(www.[a-z0-9;&#@=_~%\?\/\,\+\-]+)|');
$replace = array('$1', '$1', '$1');
$text = preg_replace($search, $replace, $text);
return $text;
这个在一定情况下是好使的,但是一旦输入例如 http://oa.socoo.cn/wzxing55/project/aclass_route.php?route=nt&classid=28 这种带参数的就会匹配多余的东西出来的还有html,我觉得是因为 匹配上了数组中的几个。
最后经过修改出现一个版本,请大家相互学习
$reg = '|(http://[a-z0-9;&#@=_~%\?\/\.\,\+\-]+)|';
$reg1 = '|(https://[a-z0-9;&#@=_~%\?\/\.\,\+\-]+)|';
$reg2 = '|([a-z0-9].[a-z0-9;&#@=_~%\?\/\,\.\+\-]+)|';
if(preg_match($reg,$text)){
$replace = '$1';
$text = preg_replace($reg, $replace, $text);
return $text;
}else if(preg_match($reg1,$text)){
$replace = '$1';
$text = preg_replace($reg1, $replace, $text);
return $text;
}else if(preg_match($reg2,$text)){
$replace = '$1';
$text = preg_replace($reg2, $replace, $text);
return $text;
}
|
|
|