2

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.

PeskyPotato
  • 620
  • 7
  • 18
somesh
  • 378
  • 5
  • 20

1 Answers1

5

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.

chris85
  • 23,255
  • 7
  • 28
  • 45
  • 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 Jun 05 '17 at 04:19
  • @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) – chris85 Jun 05 '17 at 04:26
  • 1
    A slight improvement \d{1,2}\/\d{1,2}\/\d{2,4} – Diego Ponciano Oct 25 '18 at 21:43