Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: Regex to replace dash only if there are specific word and number before it

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

You can use

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

See the regex demo

Details:

  • \b – a word boundary
  • from – a word from
  • \s+ – one or more whitespace
  • \d{1,2}:\d{2} – one or two digits, :, two digits
  • \K – omit the matched text
  • - – a hyphen
  • (?=\d{1,2}:\d{2}(?!\d)) – immediately on the right, there must be one or two digits, :, two digits not followed with another digit.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading