服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - PHP教程 - php将url地址转化为完整的a标签链接代码(php为url地址添加a标签)

php将url地址转化为完整的a标签链接代码(php为url地址添加a标签)

2020-06-05 15:56PHP教程网 PHP教程

这篇文章主要介绍了php为url地址添加a标签的示例,大家参考使用吧

需要提取的内容如下:

 

复制代码 代码如下:

<a href="http://baidu.com">http://baidu.com</a>这是第一个A标签,
<a href="http://blog.baidu.com">成长脚印-专注于互联网发展</a>这是第二个A标签。
https://www.zzvips.com这是第一个需要被提取的URL地址,
http://blog.baidu.com这是第二个需要被提取的URL地址'。
<img border="0" id="code40204">


function linkAdd($content){
 //提取替换出所有A标签(统一标记<{link}>)
 preg_match_all('/<a.*?href=".*?".*?>.*?</a>/i',$content,$linkList);
 $linkList=$linkList[0];
 $str=preg_replace('/<a.*?href=".*?".*?>.*?</a>/i','<{link}>',$content);

 

 //提取替换出所有的IMG标签(统一标记<{img}>)
 preg_match_all('/<img[^>]+>/im',$content,$imgList);
 $imgList=$imgList[0];
 $str=preg_replace('/<img[^>]+>/im','<{img}>',$str);

 //提取替换标准的URL地址
 $str=preg_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_/+.~#?&//=]+)','<a href="\0" target="_blank">\0</a>',$str);

 //还原A统一标记为原来的A标签
 $arrLen=count($linkList);
 for($i=0;$i<$arrLen;$i++){
  $str=preg_replace('/<{link}>/',$linkList[$i],$str,1);
 }

 //还原IMG统一标记为原来的IMG标签
 $arrLen2=count($imgList);
 for($i=0;$i<$arrLen2;$i++){
  $str=preg_replace('/<{img}>/',$imgList[$i],$str,1);
 }

 return $str;
}

$content='
<a href="http://baidu.com">http://baidu.com</a>这是第一个A标签,
<a href="http://blog.baidu.com">成长脚印-专注于互联网发展</a>这是第二个A标签。
https://www.zzvips.com这是第一个需要被提取的URL地址,
http://blog.baidu.com这是第二个需要被提取的URL地址。
<img border="0" id="code18178">
<a href="http://baidu.com">http://baidu.com</a>这是第一个A标签, <a href="http://blog.baidu.com">成长脚印-专注于互联网发展</a>这是第二个A标签。 <a href="https://www.zzvips.com" target="_blank">https://www.zzvips.com</a>这是第一个需要被提取的URL地址, <a href="http://blog.baidu.com" target="_blank">http://blog.baidu.com</a>这是第二个需要被提取的URL地址。
<img border="0" id="code57699">


/**
 * PHP 版本 在 Silva 代码的基础上修改的
 * 将URL地址转化为完整的A标签链接代码
 */

 

function replace_URLtolink($text) {
    // grab anything that looks like a URL...
    $urls = array();

    // build the patterns
    $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';

    // Get the URLs
    $c = preg_match_all($pattern, $text, $m);

    if ($c) {
        $urls = $m[0];
    }

    // Replace all the URLs
    if (! empty($urls)) {
        foreach ($urls as $url) {
            $pos = strpos('http://', $url);

            if (($pos && $pos != 0) || !$pos) {
                $fullurl = 'http://'.$url;
            } else {
                $fullurl = $url;
            }

            $link = ''.$url.'';

            $text = str_replace($url, $link, $text);
        }
    }

    return $text;
}

 

延伸 · 阅读

精彩推荐