5

I need to extract the date from a string, below is my code and the string.

$str = "Updated status to Masters - Software Engineering (Enrolled-
           Documents to Send) on 03/06/2014 14:10 by Rabih Haddad  .";


if(preg_match_all('/.*([A-Za-z]{3,4}, [A-Za-z]{3,4} [\d]{1,2}, [\d]{4}).*/',$str,$matches))
{
    print_r($matches);
}
 else
  echo "not matched";

How can I extract date(03/06/2014) value from the string.

5
  • @chris85 i tried but i am not getting Commented Jun 5, 2017 at 3:20
  • Yes it's working @chris85 Commented Jun 5, 2017 at 3:31
  • Okay, I've moved that to an answer. Commented Jun 5, 2017 at 3:37
  • 2
    Possible duplicate of Regex to validate date format dd/mm/yyyy Commented Jun 5, 2017 at 4:14
  • @chiris Sure... Commented Jun 14, 2017 at 14:12

1 Answer 1

11

Just look for the specific format you are after, 2 numbers then a forward slash, 2 more numbers then another forward slash, then 4 numbers.

\d{2}\/\d{2}\/\d{4}

PHP Usage:

preg_match_all('/\d{2}\/\d{2}\/\d{4}/',$str,$matches)

Demo: https://eval.in/811793

Your regex is looking for characters that aren't present. For example [A-Za-z]{3,4} [\d]{1,2}, [\d] {4}).* is looking for 3 or 4 alpha characters, a space 1-2 numbers, a comma, a space, a number, a new line, 4 spaces, and then anything after that.

Your {4} was correct you just needed to put it on the \d. The \d also doesn't need to be in a character class.

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

3 Comments

What do you think about this meta request.... To help OP's and reward duplicate hunting, if the OP finds the posted duplicate link sufficient to solve the snowflake issue, then the +15 could go to the first person to nominate the suitable link. Do you think that could work? It should promote helpers looking very carefully at the question and giving the best "possible duplicate". Perhaps the message would take on a different feel (versus the "your message is a duplicate, so I am going to try to silence you").
@mickmackusa Link didn't include. I can rarely find good dups though, sometimes even when I know the rough title (prevent sql injection PHP, for example) I can't find them. Since I answered I don't think it is appropriate for me to vote to close now (my answer also hopefully will explain a few more things to the OP). (Dup looks thorough though)
A slight improvement \d{1,2}\/\d{1,2}\/\d{2,4}

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.