PHP替换指定字符串后的值



我有这个字符串:$path = "[other values] and dateStart >= '2021-01-01' and dateEnd <= '2021-12-31' and [other values ...]'";

我要做的是将dateStart后的值替换为2021-02-02

我尝试使用$test = substr($path, 0, strpos($path, 'dateStart >= '));,但它只返回'dateStart'之前的所有内容…

任何想法?

如果您想要替换dateStart,您可以使用一个模式来匹配一个类似日期的模式,并用您的新字符串替换匹配。

然后你可以更新模式来替换dateEnd。

bdateStarth+>=h+'Kd{4}-d{2}-d{2}(?=')

Regex演示

$re = '/bdateStarth+>=h+'Kd{4}-d{2}-d{2}(?=')/m';
$path = "[other values] and dateStart >= '2021-01-01' and dateEnd <= '2021-12-31' and [other values ...]'";
echo preg_replace($re, '2021-02-02', $path);

输出
[other values] and dateStart >= '2021-02-02' and dateEnd <= '2021-12-31' and [other values ...]
$date = '2021-01-01';
$replace = "2021-02-02";
$path = "[other values] and dateStart >= '2021-01-01' and dateEnd <= '2021-12-31' and [other values ...]'";
$pos = strpos($path, $date);
$test = substr($path, 0, $pos);
$test = $test.$replace.substr($path, $pos + strlen($date));

最新更新