1

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

2
  • What are you trying to do? Are you attempting to change / or . into -? What output do you expect from what input? Commented Feb 6, 2014 at 13:57
  • To What could be wrong I'd say "Using preg_replace for manipulation of dates". There're great PHP functions for manipulating dates. Commented Feb 6, 2014 at 13:59

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Convert your input date into a UNIX timestamp. This is just an integer-representation of a date/time.

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');

Format that timestamp as a string that is formatted the way you want it.

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);

Output your newly formatted date.

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.

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.