i have this code to replace a pattern in a php date like this
$input = preg_replace('/\/\-\.\_\s/', '-', $date);
If i pass date in the form mm/dd/yyyy
, preg_replace just gives me back the passed date
the expected output should be mm-dd-yyyy
what could be wrong
The set of characters you intend to replace with -
belong inside a []
character class. In there, the .
does not require escaping.
$out = preg_replace('#[/._\s]#', '-', $date);
When you are dealing with /
as one of your expected characters, it is recommended to use a different character such as #
as the delimiter.
$date = '01/02/2013';
echo preg_replace('#[/._\s]#', '-', $date);
// 01-02-2013
$date = '01.02.2013';
echo preg_replace('#[/._\s]#', '-', $date);
// 01-02-2013
// Or mixed...
$date = '01 02/2013';
echo preg_replace('#[/._\s]#', '-', $date);
// 01-02-2013
In your attempt, not using a character class []
caused your expression to expect the characters /-._\s
literally in succession.
You may your heart set on using regular expressions, in which case you can disregard my answer. But if you would like to improve the set of tools that you have as a programmer, then investing some time into learning PHP's Date/Time functions may be helpful for you. Here is how I would approach your problem:
Use PHP's strtotime
function to do this (documentation here). It converts "about any English textual datetime description into a Unix timestamp."
$timestamp = strtotime('02/06/2014');
Use PHP's date
function to do this (documentation here). This is a very versatile and helpful function.
$properly_formatted_date = date('m-d-Y', $timestamp);
print $properly_formatted_date;
Granted, this solution doesn't use a regular expression. But, I don't believe your problem necessitates a regular expression. In fact, if your inputs ever change (perhaps the format of the original date is no longer mm/dd/yyyy
but instead it is yyyy-mm-dd
), you would need to change your regular expression. But strtotime
should be able to handle it, and your code wouldn't need to change.