0

I want to check whether the string is in the following format in php,

DD/MM/YYYY, HH:MM: Any string message 1, may contain any special character

above syntax should be matched with the incoming string example:

 12/01/2015, 10:15: Happy New Year 2015

How to check this format in php?

2
  • Must the first part it be a valid Date/Time as well or just digits? Commented Jan 2, 2015 at 6:44
  • just digits but should be in specified format, i'm happy if u specify for valid Date/Time also Commented Jan 2, 2015 at 6:46

1 Answer 1

1
$string = "12/01/2015, 10:15: Happy New Year 2015";

if(preg_match('/\d{2}\/\d{2}\/\d{4}\,\ \d{2}:\d{2}:.*/', $string)) {
        echo "$string passed check.";
}

Now if you want to ensure that the first part is a valid DateTime format, you can do that too, but it wasn't clear from your request.

Edit: Based on your followup, you could do something like this:

$string = "12/01/2015, 10:15: Happy New Year 2015";

function validate($string)
{
        if(preg_match('/\d{2}\/\d{2}\/\d{4}\,\ \d{2}:\d{2}:.*/', $string)) {
                $split = preg_split('/:\ /', $string);
                $date = str_replace(', ', ':', $split[0]);
                $d = DateTime::createFromFormat('m/d/Y:H:i', $date);
                return $d && $d->format('m/d/Y:H:i') == $date;
        }
        return false;
}

var_dump(validate($string));

It just extracts the date section, and verifies that it's a valid DateTime object. I left the preg_match() in because it will ensure that the data coming in is appropriate for the Date validation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.