skip to Main Content

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.

2

Answers


  1. 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}sd{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
    
    Login or Signup to reply.
  2. 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

    If trim is not sufficient for special cases or if only certain date formats are to be accepted, a preg_replace can be used instead of trim.

    preg_replace('/^[^d]*(.+?)[a-z ,]*$/iu','$1',$status);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search