简体   繁体   中英

regex/php: parse times from string?

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!!

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 )
/*
preg_match_all('/\d{2}:\d{2}/', $string, $matches);

您将所有匹配项放入$matches数组中。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM