How to remove external links in php

藏色散人
Release: 2023-03-06 15:22:02
Original
2726 people have browsed it

php去除外链的方法:首先打开相应的PHP文件;然后通过定义的“Replace_Links”方法处理下文章内容;最后完成文章外部链接的自动删除即可。

How to remove external links in php

推荐:《PHP视频教程

一般在做网站系统的时候,出于优化等因素的考虑需要再添加文章的时候删除掉不是本站的链接,对于这一要求可以通过让PHP处理下文章内容,来达到文章外部链接的自动删除的效果。

本实例代码主要参考织梦CMS内容管理系统的外链删除方法。

代码如下:

/**
 *  删除非站内链接
 *
 * @access    public
 * @param     string  $body  内容
 * @param     array  $allow_urls  允许的超链接
 * @return    string
 */
function Replace_Links( &$body, $allow_urls=array()  )
{
    $host_rule = join('|', $allow_urls);
    $host_rule = preg_replace("#[\n\r]#", '', $host_rule);
    $host_rule = str_replace('.', "\\.", $host_rule);
    $host_rule = str_replace('/', "\\/", $host_rule);
    $arr = '';
    preg_match_all("#<a([^>]*)>(.*)<\/a>#iU", $body, $arr);
    if( is_array($arr[0]) )
    {
        $rparr = array();
        $tgarr = array();
        foreach($arr[0] as $i=>$v)
        {
            if( $host_rule != &#39;&#39; && preg_match(&#39;#&#39;.$host_rule.&#39;#i&#39;, $arr[1][$i]) )
            {
                continue;
            } else {
                $rparr[] = $v;
                $tgarr[] = $arr[2][$i];
            }
        }
        if( !empty($rparr) )
        {
            $body = str_replace($rparr, $tgarr, $body);
        }
    }
    $arr = $rparr = $tgarr = &#39;&#39;;
    return $body;
}
Copy after login

The above is the detailed content of How to remove external links in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template