0

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?

4
  • If you change dateStart with 2021-02-02, will it make sense, because the end date will be smaller? Commented Jan 24, 2021 at 10:45
  • 1
    substr Returns the portion of string specified by the offset and length parameters. and strpos will Find the numeric position of the first occurrence of needle in the haystack string. There is no notion of 2021-02-02 as a replacement in the code. Commented Jan 24, 2021 at 10:46
  • 1
    @nice_dev, no as I need to change multiple values (like dateStart & dateEnd) but as soon as I have one working method I can apply it to all the values I need to change; I just try too keep it simple for you guys ;) Commented Jan 24, 2021 at 10:47
  • 1
    @ddl Fair enough, regular expressions is a good start for this. Commented Jan 24, 2021 at 10:52

2 Answers 2

1

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 ...]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.