PHP 替换特定字符串后的值
PHP replace value after specific string
我有这个字符串:$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 >= '));
但它只 returns 'dateStart' 之前的所有内容 ...
有什么想法吗?
$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));
如果您想替换 dateStart,可以使用模式来匹配日期之类的模式,然后用您的新字符串替换匹配项。
然后你可以更新模式来替换 dateEnd。
\bdateStart\h+>=\h+'\K\d{4}-\d{2}-\d{2}(?=')
$re = '/\bdateStart\h+>=\h+\'\K\d{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 ...]
我有这个字符串:$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 >= '));
但它只 returns 'dateStart' 之前的所有内容 ...
有什么想法吗?
$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));
如果您想替换 dateStart,可以使用模式来匹配日期之类的模式,然后用您的新字符串替换匹配项。
然后你可以更新模式来替换 dateEnd。
\bdateStart\h+>=\h+'\K\d{4}-\d{2}-\d{2}(?=')
$re = '/\bdateStart\h+>=\h+\'\K\d{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 ...]