Home > Mobile >  How to format string like date in PHP
How to format string like date in PHP

Time:05-26

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:

  1. Parse 18052022 from the string.

  2. 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

  • Related