SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

How to Extract Time Information from a Natural Language String with a Regular Expression and PHP

       

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 w/ #php #regex #snippets #natural language

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app