php从img style attr获取图像宽度

时间:2013-01-22 14:59:29

标签: php attributes

如何从img style获取图片宽度和高度?例如:

$str = '<img style="margin-right:10px;width:37px;border:0;" src="icons/icon.png">';

如何获得width =&gt; 37px?

我认为如果我们在样式attr中写一个宽度,我们可以这样写:

style="width:37px;"(no space with semicolon)
style="width: 37px;"(space with semicolon)
style="width:37px"(no space no semicolon)
style="width: 37px"(space no semicolon)

如果没有分号,则必须在样式的末尾写入宽度,如style="height:25px;width:37px"

那么如何更容易地做到这一点?正则表达式还是dom?感谢。

1 个答案:

答案 0 :(得分:3)

$image = '<img src="" style="border-width: 10px; width: 32px;">';
preg_match('/[^-]width[: ]+([0-9]+)/', $image, $matches);
print_r($matches);

$ matches [1]应该有你的答案,这只有你传入img字符串才有效,否则它会获取其他元素宽度。