Home > Back-end >  PHP: Regex to replace dash only if there are specific word and number before it
PHP: Regex to replace dash only if there are specific word and number before it

Time:01-23

I am trying to replace a dash between two time values and replace it with the word to but only if before the first time value there is the word from

This is what I have until now, which works fine, but it matches all the cases where there are two timeframes with a dash between them.

$text = "The Spa center works 08:00-20:30 every day";
$text = preg_replace('/(\d{1,2})\-(\d{1,2})/','$1 to $2', $text);

And what I want it to trigger only if the sentence looks like that

The Spa center works from 08:00-20:30 every day

So the desired result should be

The Spa center works from 08:00 to 20:30 every day

CodePudding user response:

You may include the from keyword in your regex pattern:

$text = "The Spa center works from 08:00-20:30 every day";
$text = preg_replace('/\bfrom (\d{1,2}:\d{2})-(\d{1,2}:\d{2})/','$1 to $2', $text);
echo $text;  // The Spa center works 08:00 to 20:30 every day

CodePudding user response:

You can use

preg_replace('/\bfrom\s \d{1,2}:\d{2}\K-(?=\d{1,2}:\d{2})(?!\d)/',' to ', $text)
  • Related