Ben Sinclair
Ben Sinclair

Reputation: 3986

Getting the dimensions for some <object> HTML code using PHP

I have people inserting video code to be displayed on my website. I want to make sure those videos dimensions don't go over 590 pixels in width.

So for example it they insert a video that's 640 x 385 my script would figure out some new dimensions so that it is only 590 pixels in width (e.g: 590 x 366)... I've got all the maths and ratio stuff worked out, it's just a matter of extracting the height and width from the and then replacing those with the new dimensions.

Here is a sample of some code I would need to get the dimensions of. There is also code below but once I figure how to work out the dimensions of the I can just duplicate the code for the

<object width="640" height="385">
    <param name="movie" value="http://www.youtube.com/v/ik6N1TLL2TI&hl=en_US&fs=1"></param>
    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
    <embed src="http://www.youtube.com/v/ik6N1TLL2TI&hl=en_US&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>
</object>

I've got some code I was helped with in the past which adds a URL to links that don't have a http:// in front of them. I tried to play with the code but couldn't figure it out. If it helps, here's the original code:

$content_text = preg_replace('%
    (<a\b[^>]*?href\s*+=\s*+)  # capture first chunk of A tag in group 1
    ("|\'|)                                   # capture HREF attribute delimiter in group 2
    (?!\w++://|/)                        # ensure URL has no scheme nor abs path
    ([^"\' >]++)                         # capture relative URI path in group 3
    \2                                        # match closing delimiter for HREF attribute
    %ix', '$1"' . SITEURL . '/$3"', $content_text);

Thanks for your help in advance!

Upvotes: 1

Views: 125

Answers (1)

Jim
Jim

Reputation: 18863

Probably will get raked through the coals for this, as you should use the HTML DOM parser in PHP. But here is the regex as an "alternate" method.

preg_match('~<object.*(width|height)=(.*) (width|height)=(.*)(>|\s)~isU', $contents, $matches);
if (!empty($matches)) {
    $dimensions[strtolower($matches[1])] = str_replace(array("'", '"'), '', $matches[2]);
    $dimensions[strtolower($matches[3])] = str_replace(array("'", '"'), '', $matches[4]);
}

The HTML Parser may be a wiser choice, but the above should grab the width and height no matter the quotes or the order and will place them in $dimensions['width'] and $dimensions['height'].

Like I said, this is just an alternative example and the HTML Parser is probably the wiser way to go. Also the Regex could probably be written better as well but oh well. Hope it helps.

Upvotes: 2

Related Questions