我有这样的代码:
<object height="510" width="650">height="510"width="650">
或者这个代码:
<objectheight="345"width="123'> height='456'width=789>
值周围的引号可以是双引号、单引号或无引号。这些词可以放在一起,也可以有一个或多个空格。重要的是数字作为值可以是任何值
所以,我需要用我自己的变量$height_val
替换height="510
"(或height='123'
或height=456
)中的整数值。
我的代码:
$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>
我使用的reg-ex是:height=(["']*)[0-9]*(["']*)
。这样可以确保您只获得等号后面的任意长度数字后面的任何非alpha数字的高度值。
$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&height=515&plugins=http://
接下来,我建议您尝试使用RegEx测试器来尝试您自己的组合。你也可以使用这个regex引用来帮助你处理字符类。
更新:如果您不希望使用引号,请使用以下命令: