A-A+
PHP正则表达式匹配验证提取网址URL
在编程时遇到一个问题,就是当访客留言时,如果在留言中有网址,则自动添加网址链接,如果添加框是一个 FCK 的编辑器,那么就好办了,会自动添加链接的,而现在只是一个普通的文本域,所以需要在程序处理时进行正则的判断。
匹配网址 URL 的正则表达式:
(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)
示例:PHP 正则表达式自动匹配字符串是否为 url 地址,是的话自动加上链接。
<?php function autolink($rurl){ $rurl = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_ \+.~#?&//=]+)', '<a href="\1" target=_blank rel=nofollow>\1 </a>', $rurl); // rel=nofollow 是告诉搜索引擎不要去抓取这个链接 if( strpos($rurl "http") === FALSE ){ $rurl = eregi_replace('(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+ )', '<a href="http://\1" target=_blank rel=nofollow >\1</a>', $rurl); }else{ $rurl = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@ :%_\+.~#?&//=]+)', '\1<a href="http://\2" target=_blank rel=nofol low>\2</a>', $rurl); } return $rurl; } ?>
调用 autolink() 函数
<?php $str = 'https://www.xiariboke.net'; echo autolink($str); ?>