$re = '/^(P((?<numYears>[1-9]+[0-9]*)Y)?((?<numMonths>[1-9]+[0-9]*)M)?((?<numDays>[1-9]+[0-9]*)D)?(T((?<numHours>[1-9]+[0-9]*)H)?((?<numMinutes>[1-9]+[0-9]*)M)?((?<numSeconds>[1-9]+[0-9]*)S)?)?|P(?<numWeeks>[1-9]+[0-9]*)W)$/m';
$str = 'P1Y2M3DT4H5M6S
P1M
PT1M
P1MT1M
P1W
P1D
PT2S
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php