I have a string for example "somefile_18052022.pdf" where numbers is date - 18 of may 2022. How is it possible to remove all other characters except numbers and format that number string like "2022-05-18"?
CodePudding user response:
Parse
18052022
from the string.Create a date object from the format
dmY
, then format it to your desired output.
<?php
$string = 'somefile_18052022.pdf';
preg_match('/_(\d ).pdf$/', $string, $matches);
// 2022-05-18
echo DateTime::createFromFormat('dmY', $matches[1])->format('Y-m-d');
*validation not included