Lionel Dcosta Lionel Dcosta - 1 month ago 7
PHP Question

Find out whether string has date in it

I have a string "scbdemo2016-10-21:getlastweekReadBooks4795".
How to find out the above string has date in it and to validate the date is current day date.

Answer

Easily done with regular expressions:

$isToday = stringDateToday("scbdemo2016-10-21:getlastweekReadBooks4795");

function stringDateToday($string) {
    $reg = "/\d{4}-\d{2}-\d{2}/";

    $date = new DateTime();

    preg_match($reg, $string, $matches);

    if (isset($matches[0])) {
        return $matches[0] == $date->format("Y-m-d");
    }

    return false;
}

stringDateToday() will return true if the date in the string is today. The date can be anywhere in the string.

EDIT:

As suggested in the comments, you may want to change new DateTime() to new DateTime('now', new DateTimeZone('Europe/London')) to specify timezone.

Comments