Quantcast
Channel: User easement - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Optimize regex replace in PHP

$
0
0

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;}

Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>