ExcellentSP ExcellentSP - 4 months ago 24
PHP Question

How to pull the non delimited date and time out of a string

I need to pull the date and time out of this string:

so I can reformat it to something more work-with-able. The date and time will change from file to file, but will always stay in this format:
some_report_{year}{month}{day}_{24hr time}.xml

$test = 'some_report_20161005_1530.xml';
preg_match('(\d{4})(\d{2})(\d{2})_(\d{4})', $test, $test_matches);
print_r( $test_matches );

What would be the best way to accomplish this?

(Forgive my ignorance or misuse of these functions. I am by no means an expert)


If the some_report doesn't contain digits, the date and time parts are already in a good order to work in the DateTime constructor, so you can extract them with a simpler regex.

$date_time = new DateTime(preg_replace("/[^0-9]/", "", $your_string));