'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];


Solution 1:[1]

With DateTime::createFromFormat the expression can be completely parsed. substr is not needed. The expression after the underscore stands for a time I think.

$str = '20211215_083437.jpg';
$dt = DateTime::createFromFormat('Ymd_His.???', $str);

var_dump($dt);
//object(DateTime)#2 (3) { ["date"]=> string(26) "2021-12-15 08:34:37.000000" ..

echo $dt->format('\Y\e\a\rY \M\o\n\t\hm \D\a\yd');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jspit