1

how to get image width and height from img style? for example:

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

How to get width => 37px?

I think if we write a width in a style attr, we could write it like these:

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)

if no semicolon, the width must be write in the end of the style, like style="height:25px;width:37px"

so how to do it more easier? regex or dom? Thanks.

cj333
  • 2,547
  • 20
  • 67
  • 110
  • 4
    [Don't use regexes for parsing HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – John Conde Jan 22 '13 at 15:00
  • 1
    DOM will get you the contents of the style attribute as a single monolithic string. DOM doesn't know anything about CSS whatsoever. You'd have to CSS parsing once you get the whole string. – Marc B Jan 22 '13 at 15:01
  • Why would you do this? Wouldn't it be more useful to read the actual image sizes or the rendered CSS sizes? – feeela Jan 22 '13 at 15:01
  • @John Conde, so I need some work code, could you help me? – cj333 Jan 22 '13 at 15:01
  • 1
    I would think that once you extract the `style` attribute, a simple `explode()` against semicolons would get you each key/value pair, and another `explode()` against colons would split the keys and values from each other. – WWW Jan 22 '13 at 15:03
  • @feeela, i parse some html code, then I want to remove some image witch width < 300px (if it has width in its style attr) – cj333 Jan 22 '13 at 15:04

1 Answers1

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

$matches[1] should have your answer, and this'll only work if you only pass in the img string, otherwise it'll pick up other element widths.

Toddish
  • 516
  • 2
  • 12