-1

我有这个代码:

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

或此代码:

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

值周围的引号可以是doublesinglenone。单词可以放在一起,也可以有一个或多个空格。重要的是数字作为值可以是任何东西

所以,我需要用我自己的 variable替换height="510" (or height='123'or ) 中的整数值。height=456$height_val

到目前为止我的代码:

$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);

最后的结果应该是<objectheight="640"width="123\'> height=\'640\'width=789>

4

1 回答 1

1

我使用的正则表达式是:height=(["']*)[0-9]*(["']*). 这可确保您仅在等号之后获得任何非字母数字的高度值,然后是任意长度的数字。

$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);

我已经在以下变量上对其进行了测试:

<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://

展望未来,我建议您尝试使用RegEx 测试器来尝试您自己的组合。您还可以使用此正则表达式参考来为您提供有关字符类的帮助。

更新:如果您也希望不使用引号,请使用以下内容:

于 2013-05-20T08:35:46.820 回答