Written by Sean Behan on Mon Feb 26th 2018

You can easily extract time information from a string with a regular expression and PHP (or any language with regular expressions).

$str = "Here is how to extract time info.. like 4:30 PM and 2:10 AM from a string in PHP";
$rgx = "/\d{1,2}(:?\d{1,2})?\s?(A|P)M/i";
preg_match_all($rgx, $str, $matches);
var_dump($matches);

This will give use the following array.

array(3) {
    [0]=>
    array(2) {
        [0]=>
        string(7) "4:30 PM"
        [1]=>
        string(7) "2:10 AM"
    }
    [1]=>
    array(2) {
        [0]=>
        string(3) ":30"
        [1]=>
        string(3) ":10"
    }
    [2]=>
    array(2) {
        [0]=>
        string(1) "P"
        [1]=>
        string(1) "A"
    }
}

We can see the results we want are in the first item in the array. Calling

var_dump($matches[0]); 

Will give use the results we want without the other matches. Note this is case insensitive and supports times like 2pm or 12:30pm as well.


Tagged with..
#PHP #Regex #Snippets #Natural Language

Just finishing up brewing up some fresh ground comments...