Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract a YYYmmDD in PHP

I have images and videos from my camera which are uploaded to my server. In order to properly organize them I need to extract the year month and day. But I cant seem to get this pregmatch right..

Input would be 20211215_083437.jpg
Output would be Year2021 Month11 Day15

if (preg_match('/^(\d{4})(\d{2})(\d{2})$/', $value, $matches)) {
    $year = $matches[0];
    $month = $matches[2];
    $day = $matches[3];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to remove the $ anchor in your RegEx to make it work: it matches the end of the string but yours has content after the date.
Also, the year is the 1st capture group. The index 0 contains the complete matching string.

if (preg_match('/^(\d{4})(\d{2})(\d{2})/', $value, $matches)) {
    $year = $matches[1];
    $month = $matches[2];
    $day = $matches[3];
}

But, using a regex for this is overkill. You could sustract the date part of the filename and create a DateTime object from it:

$date_string = substr($value, 0, 8);

$date = \DateTime::createFromFormat('Ymd', $date_string);

// Format the date as you want
echo $date->format('Y-m-d');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading