0

I want to write a regex to obtain 06:00 and 06:59 out of this is the string:

06:00 Pizza Hut24 06:59

I am not able to build the proper regex! This is my regex so far but it is considering 24 in Hut24 as a part of the result but it shouldn't:

(?P<start_time>\d{2}:\d{2})\s+([a-zA-Z\s]*)(?P<end_time>\d{2}:\d{2})?
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Is this meant to be a pattern used in `preg_match_all`? – El_Vanja Mar 23 '20 at 22:34
  • @El_Vanja Yes preg_match – Jinni Shah Mar 23 '20 at 22:37
  • There are string like this 06:00 Pizza Hut 06:59 without 24 so it should match that too – Jinni Shah Mar 23 '20 at 22:40
  • Shouldn't be this enough? `\d\d:\d\d` – Eraklon Mar 23 '20 at 22:40
  • @Eraklon, keep in mind that your regex matches `"1234:5678"`. – Cary Swoveland Mar 23 '20 at 22:52
  • To visually set off blocks of code or strings on SO it's easiest to indent it 4 spaces or select the text and click on `{}` above the code-editing block. To set off code or strings surrounded by text surround it with backticks (`\``). Titles of questions are meant to provide readers with an idea of what the question is about, to help them decide if they want to look at it. Your title does not make the grade. Perhaps something like, "How to extract substrings representing times from a string". Note the "edit" button. :-) – Cary Swoveland Mar 23 '20 at 22:56

2 Answers2

0

If you want to find all the occurrences, use preg_match_all:

$string = '06:00 Pizza Hut24 06:59';
preg_match_all('/\d{2}:\d{2}/', $string, $found);
var_dump($found);

This will give

array(1) {
    [0] => array(2) {
        [0]=> string(5) "06:00"
        [1]=> string(5) "06:59"
    }
} 

So you started off well, just had to use the right function.

El_Vanja
  • 3,660
  • 4
  • 18
  • 21
0

I was able to frame an answer (although your question was not framed nicely and you didn't mention in your question that you wanted to capture Pizza Hut24) for you:

(\d{2}:\d{2})\s+([\w\d\s]+)\s+(\d{2}:\d{2})

The above regex will capture 06:00 Pizza Hut24 06:59 seperately.


Tested on the following strings:

06:00 Pizza Hut24 06:59
06:00 Pizza Hut24 06:59
16:00  Pizza Hut24    06:59
06:00 Pizza Hut11114 06:59