Search code examples
phpregexregex-lookaroundsregex-group

How to obtain hours and minutes from a string of data?


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})?

Solution

  • 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.