今天闲来无事 写了这么一个正则表达式:这个PHP的正则表达式 可以满足HTTP://协议的 所有URL地址的匹配。
可获取的URL 地址类型(www.91php.com 91php.com http://www.91php.com http://group.yidabasns.com/index.php?do=default&tag=1&gid=1003135 http://www.91php.com/hdown/200809/07-50.html)
下面请看代码 (大家可以拿去改成一个function 方法 函数 来用)
- <?php
- $newContent = "我在永余PHP技术社区发现了好多高级教程,快来看呀!www.91php.com www.g.cn http://www.baidu.com http://www.163.com/shipin.html http://www.sina.com/jscss.html";
- $pattern = "/(http:\/\/)*(www)*[\w-]*(\.)*[\w-]+\.(com|net|org|gov|cc|fm|me|biz|info|cn)(\.(cn|hk))*(\/)*([\w-\]\/\.\?\=\&])*/";
- preg_match_all($pattern, $newContent, $matches);
- //var_dump($matches);exit;
- for($i=0;$i<count($matches[0]);$i++){
- $cleanURL = str_replace("http://","",$matches[0][$i]);
- $newAddress = "<a href='http://".$cleanURL."' target='_blank'>".$cleanURL."</a>";
- $newContent = str_replace($matches[0][$i],$newAddress, $newContent);
- }
- echo $newContent;
- ?>
<?php
$newContent = "我在永余PHP技术社区发现了好多高级教程,快来看呀!www.91php.com www.g.cn http://www.baidu.com http://www.163.com/shipin.html http://www.sina.com/jscss.html";
$pattern = "/(http:\/\/)*(www)*[\w-]*(\.)*[\w-]+\.(com|net|org|gov|cc|fm|me|biz|info|cn)(\.(cn|hk))*(\/)*([\w-\]\/\.\?\=\&])*/";
preg_match_all($pattern, $newContent, $matches);
//var_dump($matches);exit;
for($i=0;$i<count($matches[0]);$i++){
$cleanURL = str_replace("http://","",$matches[0][$i]);
$newAddress = "<a href='http://".$cleanURL."' target='_blank'>".$cleanURL."</a>";
$newContent = str_replace($matches[0][$i],$newAddress, $newContent);
}
echo $newContent;
?>
以上代码有个BUG 就是 当有相同域名的时候 替换会出问题
修改后代码请查看 文章 :