Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

PHP replace value after specific string

I have this string: $path = "[other values] and dateStart >= '2021-01-01' and dateEnd <= '2021-12-31' and [other values ...]'";

What I am tring to do is to replace the value after dateStart with 2021-02-02.

I tried using $test = substr($path, 0, strpos($path, 'dateStart >= ')); but it only returns everything before 'dateStart' ...

Any ideas?

question from:https://stackoverflow.com/questions/65869561/php-replace-value-after-specific-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to want to replace the dateStart, you could use a pattern to match a date like pattern and replace the match with your new string.

Then you could update the pattern to also do the replacement for dateEnd.

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

Regex demo

$re = '/dateStarth+>=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);

Output

[other values] and dateStart >= '2021-02-02' and dateEnd <= '2021-12-31' and [other values ...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...