I'm trying to parse out a string that could have multiple values and if one doesn't exist the array is outputting the part I'm looking for up one spot, causing me logic headaches.
What I'm trying to parse: P1DT12H15M
, or PT1H5M
, or PT15M
Basically it's P(Number of Days) T(Number of Hours)(Number of Minutes). The P and T are constant. Here's the match string I have so far:
'/P([0-9]*?)D?T([1-2]?[0-9]?)H?([1-5]?[0-9]?)M?/'
It pulls everything apart, but the array output is not what I'm looking for.
PT2H gives Array ( [0] => PT2H [1] => [2] => 2 [3] => )
PT2H15M gives Array ( [0] => PT2H15M [1] => [2] => 2 [3] => 15 )
But
PT15M gives Array ( [0] => PT15M [1] => [2] => 15 [3] => )
I need that number to be in position 3, if possible.
Your input strings looks like time interval specifiers. Let the PHP internal class
DateInterval
parse them then access the properties of [DateInterval
] to get the values you need:produces:
You can access the properties directly (they are public):
If you need them as array you can even convert
$int
to anarray
and use them this way:If you insist, you can even emulate the behaviour of the
preg_match()
you struggle to create:displays:
(use
array_slice(..., 3, 6)
to keep only the time components)