...

View Full Version : preg_replace width and height wildcard in string



dprichard
02-04-2010, 12:55 PM
I am trying to wrap my head around the preg_replace thing, but it is a little confusing to me. I need to replace the width and height in an string but it needs to be a wildcard. I have it working for the width, but when I do the same thing with the height for some reason it doesn't work. It just outputs the height at the original value. Any help would be greatly appreciated.


<?php

$string = '<object width="580" height="360">';

$patterns = '/\width=".*?"/';

$replacements = 'width="250"';

$newstring = preg_replace($patterns, $replacements, $string);

$patterns = '/\height=".*?"/';

$replacements = 'height="200"';

$finalstring = preg_replace($patterns, $replacements, $newstring);

echo $finalstring;

?>

This is echoing <object width="250" height="360"> so it replaces the width, but not the height.

SKDevelopment
02-04-2010, 01:03 PM
Do not escape w and h in the beginning of your patterns. Then it will work (for this string of course - you you would like to have more complex replacement, e.g. to replace if spaces could be present before and after "=" or for some other cases, please ask questions):


<?php

$string = '<object width="580" height="360">';

$patterns = '/width=".*?"/';

$replacements = 'width="250"';

$newstring = preg_replace($patterns, $replacements, $string);

$patterns = '/height=".*?"/';

$replacements = 'height="200"';

$finalstring = preg_replace($patterns, $replacements, $newstring);

echo $finalstring;

?>

dprichard
02-04-2010, 01:25 PM
Duh, awesome, thanks!!

JAY6390
02-04-2010, 01:40 PM
One thing you should note is that it will replace all widths and heights if you are using this on a whole html file instead of just a single line. You could do this which will replace all widths and heights in one simple regex for any object as you described


$string = '<object width="580" height="360">';

$pattern = '/<object width="[^"]+" height="[^"]+">/i';
$replace = '<object width="250" height="200">';

$finalstring = preg_replace($pattern, $replace, $string);
echo $finalstring;

koko5
02-07-2010, 09:57 AM
Hi,

Here is another one line solution:


$string = '<object width="580" height="360">';
echo preg_replace("#(width|height)=[\'\"](\d)+[\'\"]#ies","(strtolower('\\1')=='width') ? \"\\1='280'\":\"\\1='200'\"",$string)."\r\n";

Regards,
Nick



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum