I am trying to match a date in PHP using preg_match, split it and assign parts of it to an array, the date looks like "20100930", here is the code I am using:
// Make the tor_from date look nicer
$nice_from = $_POST['tor_from'];
$matches = array();
$ideal_from = '';
preg_match('/\d{4}\\d{2}\\d{2}\/', $nice_from, $matches, PREG_OFFSET_CAPTURE, 0);
// if (isset($matches[0])) $nice_from = $matches[0];
echo $matches[0];
echo "<br />";
echo $matches[1];
echo "<br />";
echo $matches[2];
echo "<br />";
echo $matches[3];
echo "<br />";
Ive been using: http://php.net/manual/en/function.preg-match.php and PHP preg_match question to formulate ideas on how to do this, however I have had no luck in getting it to work. Any help would be greatly appreciated.
Although regex isn't really a good solution for parsing a date in YYYYMMDD format, let's walk through why your pattern isn't working.
Your pattern \d{4}\\d{2}\\d{2}\
says: "match 4 digits (\d{4}
), followed by a backslash character (\\
), followed by the letter d twice (d{2}
), followed by another backslash (\\
) and then finally another two d's (d{2}
)."
As you might have figure out by now, you don't want the double slashes!
\d{4}\d{2}\d{2}
Will match 4 digits, followed by 2 digits, and then another 2 digits.
Furthermore, you are not specifying any capturing groups, so your subpatterns will never be filled. What you probably meant was:
(\d{4})(\d{2})(\d{2})
See this in action at http://www.ideone.com/iAy7K. Note that there really isn't any reason in your case to be specifying the PREG_OFFSET_CAPTURE
flag (which returns the position of each match) or 0
for the offset.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With