preg_replace 替换子字符串 php 中的数字

preg_replace to replace the number in substring php

我有以下字符串

$string = 'id="0000001" did="659" interval="2" media.jpg'

我想用 0 替换间隔标记中的 2(值是动态的 0 到 1000)。我该怎么做?

我尝试了以下代码,但它替换了所有代码

$returnValue = preg_replace('/\d+/', '0', $string, -1, $count);
$returnValue = preg_replace('/(?<=interval=")\d+/', '0', $string, -1, $count);

只需添加一个 lookbehind,说明 interval=" 应该出现在您要查找的 \d+ 之前。

这是另一种不使用回顾断言的方法,但是使用回顾更酷。

preg_replace('/(interval=")(\d+)/','0', $string, -1, $count);