Page 1 of 1

preg_match issues

Posted: Mon Dec 15, 2008 10:39 pm
by Luke
I'm attempting to parse what is called a "duration" value in icalendar. It is basically a duration of time in weeks, days, hours, minutes, and seconds. A duration value typically looks like this: "P1W3DT2H3M45S" (for 1 week, 3 days, 2 hours, 3 minutes, and 45 seconds), but it can also look like this "PT2H" (2 hours). I wrote a regex to pull this information out, but it doesn't seem to want to work in some cases :(

Code: Select all

preg_match('/^[+-]?P([0-9]{1,2}[W])?([0-9]{1,2}[D])?T?([0-9]{1,2}[H])?([0-9]{1,2}[M])?([0-9]{1,2}[S])?$/i', $value, $matches);
If you pass in "P1W3DT2H3M45S", $matches looks something like this:

Code: Select all

array(6) {
  [0]=>
  string(13) "P1W3DT2H3M45S"
  [1]=>
  string(2) "1W"
  [2]=>
  string(2) "3D"
  [3]=>
  string(2) "2H"
  [4]=>
  string(2) "3M"
  [5]=>
  string(3) "45S"
}
 
But PT2H gives me this

Code: Select all

array(4) {
  [0]=>
  string(4) "PT2H"
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(2) "2H"
}

Re: preg_match issues

Posted: Mon Dec 15, 2008 11:49 pm
by requinix
What's wrong? Seems to be working fine.

Re: preg_match issues

Posted: Mon Dec 15, 2008 11:58 pm
by Luke
Yes, you're right. It is my brain that isn't working :) I was not thinking properly. I got this working really well. Not only does it accept this format, but if you pass it in a way that could be "optimized", for instance, if you pass in "P16D" (16 days), it is smart enough to correct it to "P2W2D" (2 weeks, 2 days). I am stoked :).