问题
I am trying to make a small program that searches within a timer (with this format 00d 00h 00m 00s) and returns the days into one variable, the hours into another, etc.
This is some of my code:
$time1 = "Left: 11d 21h 50m 06s <\/div>"
preg_match_all("/ .*d/i", $time1, $timematch); // Day
$time1day = $timematch[1]; // Saves to variable
preg_match_all("/ .*h/i", $time1, $timematch); // Hour
$time1hour = $timematch[1]; // Saves to variable
preg_match_all("/ .*m/i", $time1, $timematch); // Minute
$time1minute = $timematch[1]; // Saves to variable
preg_match_all("/ .*s/i", $time1, $timematch); // Second
$time1second = $timematch[1]; // Saves to variable
My regex isn't correct but I'm not sure what it should be. Any ideas?
By the way, I am using PHP4.
回答1:
This regex will do the trick:
(\d+)d (\d+)h (\d+)m (\d+)s
Each value (day, hour, minute, second) will be captured in a group.
About your regex: I don't know what do you mean by "isn't correct", but I guess it's probably failing because your regex is greedy instead of lazy (more info). Try using lazy operators, or using more specific matches (\d
instead of .
, for example).
EDIT:
I need them to be separate variables
After matching, they will be put in different locations in the resulting array. Just assign them to variables. Check out an example here.
If you have trouble understanding the resulting array structure, you may want to use the PREG_SET_ORDER
flag when calling preg_match_all
(more information here).
回答2:
If the format is always in the order you show, I wouldn't regex it. The following should get your job done:
$time1= "Left: 11d 21h 50m 06s <\/div>";
$timeStringArray = explode(" ",$timeString);
$time1day = str_replace("d","",$timeStringArray[1]);
$time1hour = str_replace("h","",$timeStringArray[2]);
$time1minute = str_replace("m","",$timeStringArray[3]);
$time1second = str_replace("s","",$timeStringArray[4]);
回答3:
If the pattern is always this, two digits plus the time letter, you can do this:
$time1 = "Left: 11d 21h 50m 06s <\/div>";
preg_match_all("/(\d{2})[dhms]/", $time1, $match);
print_r($match);
UPDATE: this function can work with 1 or 2 digits, and match all the params.
$time1 = "Left: 11d 21h 50m 06s <\/div>";
$time2 = "Left: 21h 50m 5s";
$time3 = "Left: 9m 15s";
function parseTime($str) {
$default = array('seconds', 'minutes', 'hours', 'days');
preg_match_all("/(\d{1,2})[dhms]/", $str, $time);
if (!isset($time[1]) || !is_array($time[1])) {
return null;
}
$default = array_slice($default, 0, count($time[1]));
return array_combine($default, array_reverse($time[1]));
}
print_r(parseTime($time1));
print_r(parseTime($time2));
print_r(parseTime($time3));
来源:https://stackoverflow.com/questions/18131029/preg-match-to-find-a-word-that-ends-in-a-certain-character