preg_match issues

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

preg_match issues

Post 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"
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: preg_match issues

Post by requinix »

What's wrong? Seems to be working fine.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: preg_match issues

Post 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 :).
Post Reply