开发者

PHP/regex: matching/replacing 24-hour times

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!


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.


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.


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜