首页 > 解决方案 > 删除重复值节点列表 domdocument PHP

问题描述

我正在尝试通过 Domdocument 删除下面的重复值,但是我该怎么做呢?

在此处输入图像描述

下面是设置我想要的值的函数。

所需的输出值将只是

<link href="https://fonts.googleapis.com/css2?family=Overpass" rel="stylesheet">

并不是

<link href="https://fonts.googleapis.com/css2?family=Overpass" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Overpass" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Overpass" rel="stylesheet">

功能

add_filter('the_content', 'idh_change_output_html_ampstor_webstories');
function idh_change_output_html_ampstor_webstories( $content ) {
    global $post;
    $postID = $post->ID;

    if ("web-stories" === $post->post_type && !empty($content)) {
        $dom = new DomDocument();
        $dom->loadHTML($content);
        $links = $dom->getElementsByTagName("link");

        if (!empty($links)) {
            foreach ($links as $link) {
                $string_href = $link->getAttribute("href");
                $find_link_google = "fonts.googleapis.com";

                $link_canonical = $link->getAttribute("rel") === "canonical";
                $link_font_family = $link->getAttribute("rel") === "stylesheet" && strpos($string_href, $find_link_google);

                if($link_canonical) {
                    $link->setAttribute("href", get_permalink( $postID ) );
                }

                if($link_font_family) {
                    $link->setAttribute("href", "https://fonts.googleapis.com/css2?family=Overpass");
                }
            }
        }
        return $dom->saveHTML();
    }
    return $content;
}

标签: phpwordpressdomdocument

解决方案


推荐阅读