替换特定标记中的属性名称


Replace attribute name inside specific tags

在我的新 Wordpress 主题中,我将使用一个延迟加载库,该库要求我使用 data-src 属性而不是 src 。由于我想按原样保留旧内容,因此我想使用 Wordpress 函数替换属性。忽略属性顺序并仅限于imgiframe标记的替换模式是什么?

使用解析器,这比在 html 上使用正则表达式更安全。

    $doc = new DOMDocument(1.0, 'utf-8');
    $doc->loadHTML("html string........"); //replace with your html string
    $iframes = $doc->getElementsByTagName("iframe");
    $imgs = $doc->getElementsByTagName("img");
    foreach($iframes as $iframe)
    {
        $iframe->setAttribute("data-src", $iframe->getAttribute("src") );
        $iframe->removeAttribute("src"); // optional, delete if not wanted.
    }
    foreach($imgs as $img)
    {
        $img->setAttribute("data-src", $img->getAttribute("src") );
        $img->removeAttribute("src"); // optional, delete if not wanted.
    }
    $editedHTML = $doc.saveHTML();