Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中用字符串中的多个事件和不同值替换正则表达式_Php_Regex - Fatal编程技术网

在PHP中用字符串中的多个事件和不同值替换正则表达式

在PHP中用字符串中的多个事件和不同值替换正则表达式,php,regex,Php,Regex,我有以下代码: <object height="510" width="650">height="510"width="650"> <objectheight="345"width="123'> height='456'width=789> 最后的结果应该是我使用的regex是:高度=([“]*)[0-9]*([“]*)。这可确保您仅获取高度值,该值在等号后面加上任意长度的数字,后面加上任何非字母数字 $height_val = "640"; //$p

我有以下代码:

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

最后的结果应该是
我使用的regex是:
高度=([“]*)[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);
$height\u val=“640”;
//$pattern='/height=\D[0-9]*\D/'//预注释正则表达式
$pattern=height='/([“]*)[0-9]*([“]*)/”//新正则表达式
$replacement=$height\u val;

$string='尽量不要使用preg\u replace,坚持使用preg\u replace\u callback始终解释原因,如果可能的话,谢谢。@Matthew Baker它不适用于以下情况:
value=“width=650&;height=515
知道如何修复它。否则,您的代码可以正常工作。它工作正常,但它不适用于:value=”宽度=650&;height=515你知道如何解决这个小问题吗,所以我可以选择你的答案作为正确答案吗?@Derfder看到我的答案了吗?我用替换的逻辑更新了它。应该适用于您的所有情况。不,正如我在前面的评论中所说的那样,
/height=\D[0-9]*\D/
不会影响类似于
值的内容=“宽度=650&;高度=515&;插件=http://
高度=515&将保持不变,而不是正确的
mp;高度=640&
知道如何解决这个问题吗?@Derfder在这种情况下,我们需要一个稍微复杂一点的正则表达式。我已经更新了答案,加入了一个正则表达式,该正则表达式允许“
作为选择器,或者不允许…如果有任何问题,请告诉我。@Downvoter:请提供一个解释,说明原因,以帮助阅读文章的人,并帮助回复者纠正原因。
$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://