Preg_match for date

I am trying to match a date in PHP using preg_match, split it and assign its parts to an array, the date looks like β€œ20100930”, here is the code I use:

// 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 />"; 

I used: http://php.net/manual/en/function.preg-match.php and the PHP preg_match question to formulate ideas on how to do this, however I was not lucky that it works. Any help would be greatly appreciated.

+4
source share
5 answers

Regex is not the best way to go here if the template is simple. Use substr instead:

 $date = '20100930'; $year = substr($date,0,4); $month = substr($date,4,2); $day = substr($date,6,2); 
+1
source

Although regex is actually not a good solution for parsing dates in the YYYYMMDD format, skip why your template does not work.

Your pattern \d{4}\\d{2}\\d{2}\ says: "matches 4 digits ( \d{4} ), followed by a backslash ( \\ ) followed by a letter d twice ( d{2} ), and then another backslash (), and then finally two more d ( d{2} ).

As you may have already figured out, you do not need double slashes!

 \d{4}\d{2}\d{2} 

Will correspond to 4 digits, and then 2 digits, and then 2 more digits.

In addition, you do not specify capture groups , so your subpatterns will never be filled. You probably meant:

 (\d{4})(\d{2})(\d{2}) 

See this in action at http://www.ideone.com/iAy7K . Note that in your case there is no reason to specify the flag PREG_OFFSET_CAPTURE (which returns the position of each match) or 0 for offset.

+7
source

Forget preg_match, use strtotime ():

 echo date('Y/m/d', strtotime($_POST['tor_from'])); 
+3
source

This is better using preg_match and indexed names.

 $res = preg_match("/(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})/", $date, $matches); 

And the matches will look like this :,

 array('year' => 2010, 'month' => 12, 'day' => 07); 

Greetings.

+3
source

You need to put some brackets around the patterns that you want to display in $matches . Also, I don’t think you want a double \\ between your \d , because it will avoid the second \ and leave you the corresponding literal 'd' .

0
source

All Articles