php将url地址转化为完整的a标签链接代码(php为url地址添加a标签)
php  /  管理员 发布于 7年前   215
需要提取的内容如下: 类似微博中的自动提取URL为超链接地址。即内容提取出来添加A标签,转换成真正的超链接。网上搜索了很久,没有找到一个切实可行的解决方案。大都只是简单的提取URL(A标签和IMG标签内的地址也被提取替换了),并不能满足以上需求。正则表达式中也没发现能够实现提取时过滤掉A标签的方法。于是转换了一下思路,“曲线救国”。即,先将所有的A标签和IMG标签正则替换为某一个统一的标记,然后再提取URL地址替换为超链接,最后再将统一的标记还原替换为以前的A标签和IMG标签便解决了。 //提取替换出所有的IMG标签(统一标记<{img}>) //提取替换标准的URL地址 //还原A统一标记为原来的A标签 //还原IMG统一标记为原来的IMG标签 return $str; $content=' 即为我们想要的内容。 例2, function replace_URLtolink($text) { // build the patterns // Get the URLs if ($c) { // Replace all the URLs if (($pos && $pos != 0) || !$pos) { $link = ''.$url.''; $text = str_replace($url, $link, $text); return $text; 122 在 123 在 原梓番博客 在 博主 在 1111 在
http://baidu.com这是第一个A标签,
成长脚印-专注于互联网发展这是第二个A标签。
这是第一个需要被提取的URL地址,
http://blog.baidu.com这是第二个需要被提取的URL地址'。
,这是一个IMG标签
function linkAdd($content){
//提取替换出所有A标签(统一标记<{link}>)
preg_match_all('/.*?/i',$content,$linkList);
$linkList=$linkList[0];
$str=preg_replace('/.*?/i','<{link}>',$content);
preg_match_all('/]+>/im',$content,$imgList);
$imgList=$imgList[0];
$str=preg_replace('/]+>/im','<{img}>',$str);
$str=preg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)','\0',$str);
$arrLen=count($linkList);
for($i=0;$i<$arrLen;$i++){
$str=preg_replace('/<{link}>/',$linkList[$i],$str,1);
}
$arrLen2=count($imgList);
for($i=0;$i<$arrLen2;$i++){
$str=preg_replace('/<{img}>/',$imgList[$i],$str,1);
}
}
http://baidu.com这是第一个A标签,
成长脚印-专注于互联网发展这是第二个A标签。
这是第一个需要被提取的URL地址,
http://blog.baidu.com这是第二个需要被提取的URL地址。
,这是一个IMG标签';
echo linkAdd($content);
返回的内容为:复制代码 代码如下:
http://baidu.com这是第一个A标签, 成长脚印-专注于互联网发展这是第二个A标签。 这是第一个需要被提取的URL地址, http://blog.baidu.com这是第二个需要被提取的URL地址。
,这是一个IMG标签
/**
* PHP 版本 在 Silva 代码的基础上修改的
* 将URL地址转化为完整的A标签链接代码
*/
// grab anything that looks like a URL...
$urls = array();
$scheme = '(https?://|ftps?://)?';
$www = '([w]+.)';
$ip = '(d{1,3}.d{1,3}.d{1,3}.d{1,3})';
$name = '([w0-9]+)';
$tld = '(w{2,4})';
$port = '(:[0-9]+)?';
$the_rest = '(/?([w#!:.?+=&%@!-/]+))?';
$pattern = $scheme.'('.$ip.$port.'|'.$www.$name.$tld.$port.')'.$the_rest;
$pattern = '/'.$pattern.'/is';
$c = preg_match_all($pattern, $text, $m);
$urls = $m[0];
}
if (! empty($urls)) {
foreach ($urls as $url) {
$pos = strpos('http://', $url);
$fullurl = 'http://'.$url;
} else {
$fullurl = $url;
}
}
}
}您可能感兴趣的文章:
上一条:
php使用curl访问https示例分享
下一条:
php 检查电子邮件函数(自写)
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号