somesh
somesh

Reputation: 548

how do i extract date from string using php

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.

Upvotes: 5

Views: 9567

Answers (1)

chris85
chris85

Reputation: 23892

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.

Upvotes: 11

Related Questions