Php 替换特定标记内的属性名称

Php 替换特定标记内的属性名称,php,regex,wordpress,Php,Regex,Wordpress,在我的新Wordpress主题中,我将使用一个lazyload库,它要求我使用datasrc属性,而不是src。因为我想保留旧的内容,所以我想使用Wordpress函数替换属性。什么样的替换模式会忽略属性的顺序,并且仅限于img和iframe标记?使用解析器,这比在html上使用正则表达式更安全 $doc = new DOMDocument(1.0, 'utf-8'); $doc->loadHTML("html string........"); //replace wit

在我的新Wordpress主题中,我将使用一个lazyload库,它要求我使用
datasrc
属性,而不是
src
。因为我想保留旧的内容,所以我想使用Wordpress函数替换属性。什么样的替换模式会忽略属性的顺序,并且仅限于
img
iframe
标记?

使用解析器,这比在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();

你能在延迟加载之前使用jquery吗?我更喜欢使用Wordpress函数来替换属性,这就是为什么我在寻找一个PHP解决方案,然后可能标记或说Wordpress,因为没有人会知道这与Wordpress有关。