【发布时间】:2017-08-25 17:58:41
【问题描述】:
我正在修改我制作的 WordPress 插件,它指定缺少 width 和/或 height 属性的图像尺寸。
正如您在我的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>' );
}
【问题讨论】:
标签: php arrays image multidimensional-array