Quick regex question

Hi

I need to replace the width and height tags in an iframe HTML string. So for example, the input string will be:

<iframe width=“380” height=“230” src=“http://www.youtube.com/embed/1T4XMNN4bNM” frameborder=“0” allowfullscreen></iframe>

I would like the output string to be

<iframe width=“400” height=“250” src=“http://www.youtube.com/embed/1T4XMNN4bNM” frameborder=“0” allowfullscreen></iframe>

I.e. changing the width and height variables.

Is that easy to do?

Hi,
Try with str_replace():

$str = '<iframe width="380" height="230" src="http://www.youtube.com/embed/1T4XMNN4bNM" frameborder="0" allowfullscreen></iframe>';
$str = str_replace(array('width="380"', 'height="230"'), array('width="400"', 'height="250"'), $str);
echo $str;

Are the starting and ending dimensions always going to be the same then?

Is this text coming from files, or are they strings in a db?

Bah, ugly.


$width = 400;
$height = 200;
echo '<iframe width="' . $width . '" height="' . $height . '"  src="http://www.youtube.com/embed/1T4XMNN4bNM" frameborder="0"  allowfullscreen></iframe>';

Using regex is kind of pointless, putting more load on the CPU than you need to. It will only be noticeable if you are generating thousands of links, but still. The best solution here would be K. Wolfe’s assuming that the embed will remain constant. Also, I just amended the code so it will work with different videos:

$width = 400;
$height = 200;
$url = 'http://www.youtube.com/embed/1T4XMNN4bNM';
echo '<iframe width="' . $width . '" height="' . $height . '"  src="' . $url . '" frameborder="0"  allowfullscreen></iframe>';

or

$width = 400;
$height = 200;
$videoIdentifier = '1T4XMNN4bNM';
echo '<iframe width="' . $width . '" height="' . $height . '"  src="http://www.youtube.com/embed/' . $url . '" frameborder="0"  allowfullscreen></iframe>';

Really depends on the situation. Will you be dynamically generating the embed code?

If you want a flexible regex, this will do:


$html = '<iframe width=\\'380\\' height="230" src="http://www.youtube.com/embed/1T4XMNN4bNM" frameborder="0" allowfullscreen></iframe>';

$width = 400;
$height = 250;

$html = preg_replace('#(\\swidth\\s*=\\s*["\\']{0,1})\\d+(["\\']{0,1})#i', '${1}' .$width. '${2}', $html, 1);
$html = preg_replace('#(\\sheight\\s*=\\s*["\\']{0,1})\\d+(["\\']{0,1})#i', '${1}' .$height. '${2}', $html, 1);

This will work even if there is some white space around attributes, which is allowed in html, also it will work for single quotes, double quotes or no quotes at all around the numbers and of course it will work for any numbers. Don’t worry about it being slow, regex is not that slow - the above conversion takes 0.00007 seconds!