2

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

Final Solution

Thanks to @Wiktor Stribiżew help, the final solution, will match also Unicode and spaces between the two timeframes and the dash looks like that.

$text = preg_replace('/\bfrom\s+\d{1,2}:\d{2}\s*\K-(?=\s*\d{1,2}:\d{2}(?!\d))/u','$1 to $2', $text);
1
  • 1
    @WiktorStribiżew, this is also matching all the cases Commented Jan 23, 2023 at 12:13

2 Answers 2

0

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

5 Comments

just one more question. If the word is not from, but another language that is Unicode? For example instead of from, to be от. How can I do that?
@lStoilov You will need a u flag, e.g. with Russian: '/\bс\s+\d{1,2}:\d{2}\K-(?=\d{1,2}:\d{2}(?!\d))/u'. Fortunately, word boundaries in PHP are Unicode-aware when the u flag is used.
I have tried that and it didn't work... But it was my bad... I had a typo. Now it worked correctly
one last question... what if the times are written with a space before and after the dash. Like this 08:00-20:30
@lStoilov '/\bс\s+\d{1,2}:\d{2}\s*\K-(?=\s*\d{1,2}:\d{2}(?!\d))/u'
0

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})/','from $1 to $2', $text);
echo $text;  // The Spa center works from 08:00 to 20:30 every day

2 Comments

This is working but also removes the word from. So it becomes The Spa center works 08:00 to 20:30 every day
You could capture from too since that should be in the output \b(from \d{1,2}:\d{2})-(\d{1,2}:\d{2})

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.