views:

189

answers:

2

I have written a PHP function to take a video embed code that has width and a height and allow you to specify a new width. The function will then scale down the height using the appropriate scaling factor. I discovered that the width and height were not always adjacent so I make a couple of calls which I have a hunch are unnecessary. Is there a better way to/clean up do the following?

function scale_video($video_embed,$new_width = 200){

    preg_match('/width="(\d)*"/', $video_embed, $width);
    preg_match('/height="(\d)*"/', $video_embed, $height);
    $width = substr($width[0],7,-1);
    $height = substr($height[0],8,-1); 

    $scale_factor = $new_width/$width;
    $new_height = floor($height * $scale_factor);

    $video_embed = preg_replace('/width="(\d)*"/','width="'.$new_width.'"',$video_embed);
    $video_embed = preg_replace('/height="(\d)*"/','height="'.$new_height.'"',$video_embed);

    return $video_embed;
}
A: 

A better way might be to use preg_replace_callback() or the /e modifier (for "evaluate code) to set things up so that you only do one regex match per pattern, something like:

$video_embed = preg_replace_callback('/width="(\d)*"/', 'scale_video_width_callback', $video_embed);

function scale_video_width_callback($match) {
    // transform match and return transformed value
}
chaos
+4  A: 

The only thing I would advise is your regex pattern needs to be improved.

/width="(\d)*"/

Ought to be:

/width="(\d*)"/

This would give you a group for the entire value you are looking for, rather than a group per character in the pattern. This way you can then change:

$width = substr($width[0],7,-1);

into

$width = $width[1];

You can easily apply this to height as well. Your ending replacements could be turned into one call by making the first two parameters into arrays.

In summary, I suggest the following:

function scale_video($video_embed,$new_width = 200){

    // only process if both matches have results
    if(preg_match('/width="(\d+)"/', $video_embed, $width) &&
      preg_match('/height="(\d+)"/', $video_embed, $height) {

        $width = $width[1];
        $height = $height[1];

        $scale_factor = $new_width/$width;
        $new_height = floor($height * $scale_factor);

        $video_embed = preg_replace(array('/width="(\d+)"/', '/height="(\d+)"/'), array('width="'.$new_width.'"', 'height="'.$new_height.'"'), $video_embed);

    }

    return $video_embed;
}
The Wicked Flea