tags:

views:

58

answers:

3

Hi,

How can I take a line like this:

Digital Presentation (10:45), (11:30), 12:00, 12:40, 13:20, 14:00, 14:40, 15:20, 16:00, 16:40, 17:20, 18:00, 18:40, 19:20, 20:00, 20:40, 21:20, 22:00, 22:40, 23:10, 23:40.

And match all the 24 hour times so I can convert to a more human readable format using date()?

Also I want to match times in the 24:00-24:59 range too

Thanks!

+1  A: 

It's probably easiest to match something like (\d{2}):(\d{2}) (preg syntax), then convert both submatches to an integer and check whether they are in the correct range.

Thomas
+1: Exactly right. If $1 > 12, use ($1-12).'pm' else use "{$1}am".
Chris
A: 
preg_match_all('/([0-2][\d]):(\d{2})/', $string, $matches)

Now $matches[0] array contains all human readable times.

If you wish to print those along with specific date, feed each time through strtotime() function, like this

foreach ($matches[0] as $time) echo date('Y-m-d H:i:s', strtotime($time));
mr.b
If you are using $matches[0] then no need for the grouping... /[0-2]\d:\d{2}/ would work fine for preg_match_all.
null
true. i have that habbit of grouping matches. and it's there in case he decides to use $matches[1] and $matches[2] arrays to access only hours or minutes, respectively, without having to split string by :
mr.b
+1  A: 

You could use a regular expression like the following, which allows values from 00:00 through to 24:59 inclusive.

(?:[01][0-9]|2[0-4]):[0-5][0-9]

You seem to know what you're doing, so I'll only give a brief example without converting the times into date strings.

$times = array();
if (preg_match_all('/(?:[01][0-9]|2[0-4]):[0-5][0-9]/', $subject, $matches)) {
    $times = $matches[0];
}
print_r($times);

If the subject string has the chance of values like 1234:5678, which would result in false positives with the above regex, then you could wrap the pattern in \b or some other assertion to make sure the time formatted numbers lie on their own.

salathe
@mr.b: `$matches[0]` contains the whole match for all of the items (it's `preg_match_all` after all)
salathe
I'm not sure why did I imagine that it was "foreach" instead of "if" in your code. but again, it wouldn't make any sense anyway. my bad, sorry. deleted my comment.
mr.b