What I did wrong? It still returns 21-11-2016
.
$string = '21-11-2016';
$pattern = '/({0-9}(2))-({0-9}(2))-({0-9}(4))/';
$rep = "Month: $2 , Day: $1 , Year: $3";
echo preg_replace($pattern, $rep, $string);
die();
You have {..}
and (..)
at wrong place. Use:
echo preg_replace('/([0-9]{2})-([0-9]{2})-([0-9]{4})/', $rep, $string);
{...}
makes it a range and [...]
makes it a character class.
Here is the pattern you want:
$pattern = '/(\d{2})-(\d{2})-(\d{4})/';
Working example: https://3v4l.org/LYhvB
However, parsing dates with regex is not a good practice. Use built-in date functions!
Because that's not a valid regex. You've got []
and {}
reversed.
[]
defines character classes and ranges, e.g. [0-9]
is "all digits".{}
defines quantities. e.g. {2}
means "two of the previous".()
defines a capture group. (2)
is rather pointless. - you're just capturing a fixed 2
.
Since yours are backwards, you've got syntax errors from using invalid {}
ranges, and wouldn't match anything anyways.
Try
/([0-9]{2}-([0-9]{2})-([0-9]{4})/
instead
Your brackets and braces are messed up. It should be like this.
([0-9]{2})-([0-9]{2})-([0-9]{4})