-2

I have php web application and use preg_match parse the several times out of a string.

The problem is that my users may enter the times in the following formats:

  • "from 8:30 to 17:00"
  • "8 to 18"
  • "09:00 to 14:30"

So basically I want to get two times out of a string and each of those two times may either be given in H, HH or HH:MM.

There is a stackoverflow thread just for HH:MM, but (Regular expression for matching HH:MM time format) but none for my problem.

Community
  • 1
  • 1
Pascal Klein
  • 23,665
  • 24
  • 82
  • 119
  • Or those your only allowed, fixed formats, or are these examples of what users enter? English only, or other languages as well? – Wrikken Apr 10 '15 at 10:31
  • I am not if this you needed. `preg_match("/((2[0-3]|[01][0-9]):[0-5][0-9]))|(2[0-3]|[01][0-9]))|([0-5][0-9])/", $foo)` – terminal ninja Apr 10 '15 at 10:39
  • 1
    For anyone that downvotes, I would be glad to receive a small comment, on why. – Pascal Klein Apr 10 '15 at 10:54
  • @Wrikken: The user can enter the time however she/he wants, but the examples I mentioned are the only formats they my users are using so far. – Pascal Klein Apr 10 '15 at 10:55
  • 1
    @PascalKlein: I don't think the downvotes are fair, I can think of 2 reasons: (1) you don't show your current effort before you've asked SO, and (2) this isn't something that regexes are quite suited to, as the possibilities of adding times are endless. If you want to keep the input totally format-less, you're going to have a tough time coming up with something acceptable at first, and will be haunted by 'bug'-reports for a long time to come. There's a reason people tend to go for structured from & to hours & minutes inputs, it makes sense both financially and reliability wise. – Wrikken Apr 10 '15 at 12:03
  • @Wrikken: Thanks, but both points you mention make sense. I will take more time into drafting the question next time – Pascal Klein Apr 10 '15 at 12:19

2 Answers2

0

The quick answer (could possibly be tidied up) : (\d\d?(?::\d\d)?)\s+to\s+(\d\d?(?::\d\d)?)

See RegEx101

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
0

Without any control, it's up to you to validate the times later:

^\D*(\d\d?(?::\d\d)?)\D+(\d\d?(?::\d\d)?)\D*$

You can, of course, test that hour is between 0 and 23 and minute between 0 and 59:

^\D*((?:2[0-3]|[01]?[0-9])(?::[0-5][0-9])?)\D+((?:2[0-3]|[01]?[0-9])(?::[0-5][0-9])?))\D*$
Toto
  • 89,455
  • 62
  • 89
  • 125