在PHP中的字符串中使用多次出现和不同值的正则表达式替换

在PHP中的字符串中使用多次出现和不同值的正则表达式替换

问题描述:

I have this code:

<object height="510"   width="650">height="510"width="650">

or this code:

<objectheight="345"width="123'> height='456'width=789>

The quotes around the values could be double, single or none. And the words could be put together or there could be one or more whitespaces. And what is important the digits as a value could be anything

So, I need to replace the integervalue in height="510" (or height='123' or height=456) with my own variable $height_val.

My code so far:

$height_val = "640";
$pattern = ??? // this regex I need to find out
$replacement = $height_val;
$string = '<objectheight="345"width="123\'> height=\'456\'width=789>'
$result = preg_replace($pattern, $replacement, $string);

And the final result should be <objectheight="640"width="123\'> height=\'640\'width=789>

The reg-ex I'd use is: height=(["']*)[0-9]*(["']*). This ensures you only get the height value with any non-alpha digit after the equals followed by an any length number.

$height_val = "640";
//$pattern = '/height=\D[0-9]*\D/' // pre comments regex
$pattern = height='/(["']*)[0-9]*(["']*)/'; //new regex
$replacement = $height_val;
$string = '<objectheight="345"width="123\'> height=\'456\'width=789>'
$result = preg_replace($pattern, $replacement, $string);

I've tested it on the following variables:

<object height="510"   width="650">height="510"width="650">
<objectheight="510"   width="650">height="510"width="650">
<object height='510'   width="650">height="510"width="650">
<objectheight='510'width="650">height="510"width="650">
value="width=650&amp;height=515&amp;plugins=http://

Going forward I would recommend you try using a RegEx tester to try your own combinations. You can also use this regex reference to give you help with character classes.

Updated: If you wish to allow for no quotation marks too use the following: