Search code examples
phpstringreplacestr-replacestrpos

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?


Solution

  • 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.

    \bdateStart\h+>=\h+'\K\d{4}-\d{2}-\d{2}(?=')
    

    Regex demo

    $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);
    

    Output

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