views:

499

answers:

2

I'm trying to do a simple task of altering thousands of music video embed codes with a common with/height.

For example, I have the following code:

<object width="480px" height="407px" >
    <param name="allowFullScreen" value="true"/>
    <param name="wmode" value="transparent"/>
    <param name="movie" value="http://mediaservices.myspace.com/services/media/embed.aspx/m=1311720,t=1,mt=video"/&gt;
    <embed src="http://mediaservices.myspace.com/services/media/embed.aspx/m=1311720,t=1,mt=video"
        width="480" height="407" allowFullScreen="true"
        type="application/x-shockwave-flash"
        wmode="transparent">
    </embed>
</object>

Line breaks added only for legibility

I need to edit the width/height parameters in both the <object> and <embed> tags, one having a 'px' suffix, and the other not having one at all (which is totally random, some codes have it in all cases, others do not).

Firstly, I'm trying to find out the width/height of the existing video.... finding the aspect ratio... and then replacing the existing values with the new values (width = "640" and height="xxx" which is based on the aspect ratio of the video).

+2  A: 

Here's how to get the width and height

preg_match('/width="(\d+)(px)?" height="(\d+)(px)?"/', $text, $matches);

$width = intval($matches[1]);
$height = intval($matches[3]);

Calculate the new height like this:

$new_width = 640;
$new_height = intval($new_width * $height / $width);

And replace like so:

$text = preg_replace('/width="(\d+)(px)?" height="(\d+)(px)?"/',
                     'width="' . $new_width . '" height="' . $new_height . '"',
                      $text);
yjerem
+1  A: 

Using SimpleHTMLDOM:

require_once("simplehtmldom.php");

$dom = str_get_html($text);
foreach ($dom->find('object') as $obj) {
    $width = intval($obj->width);
    $height = intval($obj->height);
    $height = intval(640 * $height / $width);
    $obj->width = 640;
    $obj->height = $height;
    $embed = $obj->find('embed',0);
    if ($embed != null) {
        $embed->width = 640;
        $embed->height = $height;
    }
}
$text = $dom->save();
MizardX