I have this string from eBay Web-Service.
// 2Days 23Hours 37Minutes 50Seconds
$string = P2DT23H37M50S
I was using the following code to extract and time and date:
$daysLeft = substr($string, 1, 1) . " Days";
$hoursLeft = substr($string, 4, 2) . " Hours"; $minutesLeft = substr($string, 7, 2) . " Minutes"; $secondsLeft = substr($string, 10, 2) . " Seconds";
But the problem is, When the hours, minutes and dates are only 1 Digit, the strings gets all messed开发者_StackOverflow up, I had it working initially, but I'm kind of stuck to find a simple way to do it, I was going to write it in a bunch of If statements, but really want a more simple way to do this.
How about using sscanf (the opposite of sprintf)?
list($daysLeft, $hoursLeft, $minutesLeft, $secondsLeft) = sscanf($string, "P%dDT%dH%dM%DS ");
If you now that all fields always is there, just preg_split the string on non-numbers:
$fields = preg_split('[^0-9]+', $string);
$daysLeft = $fields[1] . " Days";
$hoursLeft = $fields[2] . " Hours";
$minutesLeft = $fields[3] . " Minutes";
$secondsLeft = $fields[4] . " Seconds";
精彩评论