Home > Net >  How to find and extract date in string with PHP?
How to find and extract date in string with PHP?

Time:11-15

How can i find date inside a string in PHP and extract it?'

example: I have a date in string

$status = "OK, 26.10.2022 13:24:00, Delivered Zak";

but also next time i can only get string which looks like this:

$status = "28.10.2022 11:20:00, Delivered";

So explode it to the pieces by "," is not a option here, because everytime is in different position. How can i get this date everytime? Thanks for any suggestion.

CodePudding user response:

You can use a regular expression to get the date in the string :


// examples
$statuses = [
    "OK, 26.10.2022 13:24:00, Delivered Zak",
    "28.10.2022 11:20:00, Delivered",
    ];

foreach ($statuses as $status) {

    // Grab 'xx.xx.xxxx xx:xx.xx' 
    preg_match('~\d{2}.\d{2}.\d{4}\s\d{2}:\d{2}:\d{2}~', $status, $matches);


    // Convert to date 
    // TODO : test if $matches is not empty
    $date = DateTime::createFromFormat("d.m.Y H:i:s", reset($matches));

    // echo formatted for the test
    echo $date->format("Y-m-d H:i:s")."\n";
}

Output:

2022-10-26 13:24:00
2022-10-28 11:20:00

CodePudding user response:

This solution uses trim to remove spurious characters before and after the date expression. A..Z removes all uppercase letters. Simply using date_create will also recognize some other date formats.

$statuses = [
    "OK, 26.10.2022 13:24:00, Delivered Zak",
    "28.10.2022 11:20:00, Delivered",
    "christmas eve 24 Dec 2020 19:00",
    "ABC 2022-09-12 13:45, and so on",
];
foreach ($statuses as $status) {
    $date = date_create(trim($status,"A..Za..z, "));
    echo $date->format("Y-m-d H:i:s")."<br>\n";
}

Output:

2022-10-26 13:24:00
2022-10-28 11:20:00
2020-12-24 19:00:00
2022-09-12 13:45:00

Demo: https://3v4l.org/uqAmm

  • Related