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