0
我正在重新制作一個WordPress插件,它指定了缺少width
和/或height
屬性的圖像尺寸。重印<img>具有所有屬性的標籤
正如您在我的current version on GitHub中看到的,我手動列出了<img>
標記(L38)的所有屬性。但是,如果用戶要添加自定義屬性,它會得到忽略了,因爲它不是在我的$attributes
變量中列出:
# Before
<img src="http://example.com/img.png" class="img" data-sample="test">
# After
<img src="http://example.com/img.png" class="img" width="100" height="30">
創建一個簡單的測試文件,我是能夠更新的正則表達式來存儲所有屬性在<img>
標籤中找到。是的,我意識到使用DOMDocument的建議,但它在過去導致了更多的WordPress問題。
preg_match_all('/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images);
爲了不填補這一職位有太多的代碼,我目前的工作測試文件on my GitHub Gist here。
使用var_dump($images);
,這給了我從我的樣本圖像輸出如下(我在每個數組的末尾添加...
以節省空間):
0 =>
array (size=19)
0 => string '<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG"' (length=63)
1 => string ' alt="JPG"' (length=10)
2 => string '<img src="https://placehold.it/250x100.gif?text=GIF"' (length=52)
...
1 =>
array (size=19)
0 => string 'src' (length=3)
1 => string 'alt' (length=3)
2 => string 'src' (length=3)
...
2 =>
array (size=19)
0 => string 'https://placehold.it/250x100/99cc00/000.jpg?text=JPG' (length=52)
1 => string 'JPG' (length=3)
2 => string 'https://placehold.it/250x100.gif?text=GIF' (length=41)
...
我的目標是與所有的重建圖像標記計算維度後的屬性和值。從我的測試中,我嘗試以下,但它並沒有給我結果我期待:
foreach ($images[1] as $attributes[1] => $value) {
echo('< img ' . $value . '="' . 'value' . '" ><br>');
}