tags:

views:

37

answers:

3

What is the best way to parse time from a string?

Example string: "this is 10:45 this is 10:48, 10:49, 10:50, 22:15";

Expected return:

[0] = 10:45

[1] = 10:48

[2] = 10:49

[3] = 10:50

[4] = 22:15

Thanks for any replies!!

A: 

That looks like a pretty simple case. try preg_match_all with "/\d\d:\d\d/"

Devin Ceartas
+2  A: 
preg_match_all('/\d{2}:\d{2}/', $string, $matches);

You will have all your matches in $matches array.

RaYell
You'll only have all matches if you use `preg_match_all()`
Chris Lutz
@Chris Lutz - Good point.
RaYell
+4  A: 

This will give the output you want and limits your hour/minute numbers to valid values for the first position of the hour and the first position of the minute:

$y = "this is 10:45 this is 10:48, 10:49, 10:50, 22:15";
preg_match_all("/(([0-1]\d|2[0-3]):[0-5]\d)/",$y,$matches);
print_r($matches[1]);
/*
Outputs:
Array ( [0] => 10:45 [1] => 10:48 [2] => 10:49 [3] => 10:50 [4] => 22:15 )
/*
zombat
If you wan't to match only correct times you should probably change regex to `/([0-1]\d|2[0-3]):[0-5]\d/`, yours will match also `27:00`
RaYell
That's a nice improvement, I'll edit my answer to add it in. Thanks.
zombat