-1

Let's suppose I have this date: 2016-07-27. What I want to achieve is:

$year = 2016;
$month = 07;
$day = 27;

What I have tried:

  • $year = preg_match("/^[^-]*/", "2016-07-27");
    It returns: 1
  • $month = preg_match("(?<=\-)(.*?)(?=\-)", "2016-07-27");
    It returns: Warning: preg_match(): Unknown modifier '('
  • $year = ???

How can I extract the numbers between the dashes and store them into the variables below as shown above?

Angel Politis
  • 10,955
  • 14
  • 48
  • 66
  • 1
    that's because [preg_match](http://php.net/manual/en/function.preg-match.php) returns 1 if the pattern matches, and 0 if not. Have you searched Google or SO posts with your issue yet? – swlim Jul 02 '16 at 13:19
  • 1
    [How to get year and month from a date - PHP](http://stackoverflow.com/questions/8967970/how-to-get-year-and-month-from-a-date-php) **&&** [Split string from a date](http://stackoverflow.com/q/3524881/4577762) **&&** [How to split date (08-17-2011) into month, day, year?](http://stackoverflow.com/q/7103617/4577762) (Some might not be exact duplicates, but they certainly help) @JohnConde – FirstOne Jul 02 '16 at 13:21

2 Answers2

4

Don't reinvent the wheel - date_parse will do all the heavy lifting for you:

$parsed = date_parse('2016-07-27');
$year = $parsed['year'];
$month = $parsed['month'];
$day = $parsed['day'];
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

If it's a string that wont change its format, then you can simply do this:

$date = '2016-07-27';
list($year, $month, $day) = explode('-', $date);

echo $year; // 2016
echo $month; // 07
echo $day; // 27

However, if the date format changes, then you should use date_parse or other DateTime methods.

Martin
  • 22,212
  • 11
  • 70
  • 132
aborted
  • 4,481
  • 14
  • 69
  • 132