我有这段代码:
<object height="510" width="650">height="510"width="650">
或此代码:
<objectheight="345"width="123'> height='456'width=789>
值的引号可以是 double ,单或 none 。这些词可以放在一起,也可以有一个或多个空格。重要的是数字作为值可以是任何东西
因此,我需要将height="510
“(或height='123'
或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>
答案 0 :(得分:1)
我使用的注册表是: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 tester尝试自己的组合。您也可以使用此regex reference为您提供角色类的帮助。
更新: 如果您希望不允许引号,请使用以下命令: