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];
Advertisement
Answer
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');