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>');
}