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.

6
  • 4
    Don't use regexes for parsing HTML Commented Jan 22, 2013 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. Commented Jan 22, 2013 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? Commented Jan 22, 2013 at 15:01
  • @John Conde, so I need some work code, could you help me? Commented Jan 22, 2013 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. Commented Jan 22, 2013 at 15:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

border-width: 10px will match it.
True, should have spotted that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.