我如何从页面上删除重复的链接,除了第一个 [英] How do i remove duplicate links from a page except first

查看:108
本文介绍了我如何从页面上删除重复的链接,除了第一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对某些内容有问题,这些内容一次又一次地具有相同的链接,因此我想删除除单个链接之外的所有重复链接,有人知道如何执行此操作吗???

I have a problem with some contents, which have the same link again and again, so i want to remove all duplicate links except a single, have anyone idea how to do this????

这是我的代码,该代码删除了所有链接

function anchor_remover($page) {
    $filter_text = preg_replace("|<<blink>a *<blink>href=\<blink>"(.*)\">(.*)</a>|","\\2",$page); 
    return $filter_text; 
}

add_filter('the_content', 'anchor_remover');

基本上,对于wordpress来说,我需要这样做,以过滤内容并删除重复的链接,而该链接应该只有一个链接.

basically i need this for wordpress, to filter the contents and remove duplicate links should have only a single link.

推荐答案

使用preg_replace_callback:

Using preg_replace_callback:

<?php
/*
 * vim: ts=4 sw=4 fdm=marker noet
 */
$page = file_get_contents('./dupes.html');

function do_strip_link($matches)
{
        static $seen = array();

        if( in_array($matches[1], $seen) )
        {
                return $matches[2];
        }
        else
        {
                $seen[] = $matches[1];
                return $matches[0];
        }
}
function strip_dupe_links($page)
{
        return preg_replace_callback(
                '|<a\s+href="(.*?)">(.*?)</a>|',
                do_strip_link,
                $page
        );
}

$page = strip_dupe_links($page);
echo $page;

输入:

<html>
        <head><title>Hi!</title></head>
        <body>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="foo.html">foo</a>
                <a href="bar.html">bar</a>
        </body>
</html>

输出:

<html>
        <head><title>Hi!</title></head>
        <body>
                <a href="foo.html">foo</a>
                foo
                foo
                foo
                foo
                foo
                foo
                foo
                foo
                foo
                <a href="bar.html">bar</a>
        </body>
</html>

这篇关于我如何从页面上删除重复的链接,除了第一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆