这是第二个A标签。@H_502_5@//www.jb51.cc这是第一个需要被提取的URL地址,@H_502_5@http://blog.baidu.com这是第二个需要被提取的URL地址'。@H_502_5@
类似微博中的自动提取URL为超链接地址。即内容提取出来添加A标签,转换成真正的超链接。网上搜索了很久,没有找到一个切实可行的解决方案。大都只是简单的提取URL(A标签和img标签内的地址也被提取替换了),并不能满足以上需求。正则表达式中也没发现能够实现提取时过滤掉A标签的方法。于是转换了一下思路,“曲线救国”。即,先将所有的A标签和img标签正则替换为某一个统一的标记,然后再提取URL地址替换为超链接,最后再将统一的标记还原替换为以前的A标签和img标签便解决了。
//提取替换出所有的img标签(统一标记<{img}>)@H_502_5@preg_match_all('/]+>/im',$imgList);@H_502_5@$imgList=$imgList[0];@H_502_5@$str=preg_replace('/
]+>/im','<{img}>',$str);//提取替换标准的URL地址@H_502_5@$str=preg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)','',$str);//还原A统一标记为原来的A标签@H_502_5@$arrLen=count($linkList);@H_502_5@for($i=0;$i<$arrLen;$i++){@H_502_5@ $str=preg_replace('/<{link}>/',$linkList[$i],$str,1); @H_502_5@}//还原IMG统一标记为原来的img标签@H_502_5@$arrLen2=count($imgList);@H_502_5@for($i=0;$i<$arrLen2;$i++){@H_502_5@ $str=preg_replace('/<{img}>/',$imgList[$i],1); @H_502_5@}return $str;@H_502_5@}
$content='@H_502_5@这是第一个A标签,
这是第二个A标签。@H_502_5@//www.jb51.cc这是第一个需要被提取的URL地址,@H_502_5@http://blog.baidu.com这是第二个需要被提取的URL地址。@H_502_5@logo_zh-cn.gif">,这是一个img标签';@H_502_5@echo linkAdd($content);@H_502_5@
即为我们想要的内容。
例2,@H_502_5@
function replace_URLtolink($text) {@H_502_5@ // grab anything that looks like a URL...@H_502_5@ $urls = array(); // build the patterns@H_502_5@ $scheme = '(https?://|ftps?://)?';@H_502_5@ $www = '([w]+.)';@H_502_5@ $ip = '(d{1,3}.d{1,3})';@H_502_5@ $name = '([w0-9]+)';@H_502_5@ $tld = '(w{2,4})';@H_502_5@ $port = '(:[0-9]+)?';@H_502_5@ $the_rest = '(/?([w#!:.?+=&%@!-/]+))?';@H_502_5@ $pattern = $scheme.'('.$ip.$port.'|'.$www.$name.$tld.$port.')'.$the_rest;@H_502_5@ $pattern = '/'.$pattern.'/is'; // Get the URLs@H_502_5@ $c = preg_match_all($pattern,$text,$m); if ($c) {@H_502_5@ $urls = $m[0];@H_502_5@ } // Replace all the URLs@H_502_5@ if (! empty($urls)) {@H_502_5@ foreach ($urls as $url) {@H_502_5@ $pos = strpos('http://',$url); if (($pos && $pos != 0) || !$pos) {@H_502_5@ $fullurl = 'http://'.$url;@H_502_5@ } else {@H_502_5@ $fullurl = $url;@H_502_5@ } $link = ''.$url.''; $text = str_replace($url,$link,$text);@H_502_5@ }@H_502_5@ } return $text;@H_502_5@}@H_502_5@