【问题标题】:Replace attribute name inside specific tags替换特定标签内的属性名称
【发布时间】:2015-01-09 20:56:45
【问题描述】:

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

【问题讨论】:

  • 你可以在延迟加载之前使用jquery吗?
  • 我更喜欢使用 Wordpress 的函数来替换属性,这就是我寻找 PHP 解决方案的原因
  • 哦,那么也许可以标记或说 wordpress,因为没有人会知道这与 wordpress 有什么关系。

标签: php regex wordpress


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多