1

I have a string date like this:

$date = "23/12/2011";//format: dd/mm/yyyy.

I need each part of this date in its own variable, so that $d=="23", $m=="12", and $y=="2011".

Any suggestions on how to do this would be appreciated...

1
  • 3
    Regular expressions: enjoy responsibly. Commented Dec 5, 2011 at 18:16

5 Answers 5

7

You could just do:

list($day, $month, $year) = split("[/]", $yourDate);
Sign up to request clarification or add additional context in comments.

5 Comments

explode() should be used over split() in this case.
@TimCooper Am I correct in understanding that to mean there is an appreciable performance difference between explode and split? Nevermind, the phpdocs answered that question for me.
@rdlowrey: Between explode() and split(), not explode() and list.
split() is deprecated since it uses the POSIX regex engine, you should avoid it in favour for preg_split() (RegEx splitting with limited Unicode support), mb_split() for regex splitting with unicode support or explode() for regex-less splitting.
What if you are parsing the following date string "20120924".
2
$date = "23/12/2011";
list($d,$m,$y) = explode('/', $date, 3)

Comments

1

The regex you're looking for is /(\d+)\/(\d+)\/(\d+)/ and in the preg_match they would be contained in the $matches array you define in the preg_match call.

See here: http://php.net/manual/en/function.preg-match.php

Comments

1

Backreferences:

if (preg_match('%(\d{2})/(\d{2})/(\d{4})%', $subject, $regs)) {
    $result = $regs[1]; #first two digits are here.. etc..
}

Comments

1

With this solution, each variable is automatically assigned the proper datatype:

sscanf($date, '%d/%d/%d', $d, $m, $y);

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.