2015-01-09 52 views
-1

在我的新Wordpress主題中,我將使用一個lazyload庫,該庫需要使用data-src屬性而不是src。由於我想保留舊內容,我想用Wordpress函數替換屬性。忽略屬性順序的替換模式是什麼?限於imgiframe標籤?替換特定標記內的屬性名稱

+0

可以在延遲加載之前使用jquery嗎? – Buck3y3 2015-01-09 20:59:18

+0

我寧願使用Wordpress的功能來替換屬性,這就是爲什麼我要尋找一個PHP解決方案 – idleberg 2015-01-09 21:00:40

+0

哦,然後可能標記或說wordpress,因爲沒有人會有任何線索,這與wordpress有什麼關係。 – Buck3y3 2015-01-09 21:03:54

回答

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(); 
相關問題