Search code examples
phpstringdatedatetimepreg-match

How can I grab a date out of a string and format it?


I have PDF-files on my server saved like:

945_20140610_Eve_Ikras.pdf

I want to break out the year, month and day separately.

$file = "945_20140610_Eve_Ikras.pdf";

if(preg_match("/\d{4}\-d{2}\-d{2}/", $file, $match))
    print_r($match);

Output:

Array (
  [0] => 20140610
)

But I want to format the date like this:

2014-06-10

Any suggestions?


Solution

  • The easiest way is just to create a DateTime object (Since you have a special format here you have to use DateTime::createFromFormat to create your object) and then you can format your date as you want it with format(), e.g.

    $file = "945_20140610_Eve_Ikras.pdf";
    
    if(preg_match("/\d{4}\d{2}\d{2}/", $file, $match)) {
        $date = DateTime::createFromFormat("Ymd", $match[0]);
        echo $date->format("Y-m-d");
    }
    

    output:

    2014-06-10