1

I am trying to change a string which may have a date inside e.g.

"This is the test string with 22/12/2012. 23/12/12 could anywhere in the string"

I need to change above string so that date are in the format d-m-y i.e.

"This is the test string with 22-12-2012. 23-12-12 could appear anywhere in the string"

EDIT: Please note that the date will could changed in terms of years i.e. 2012 or 12 could be used at time i.e 20/06/2012, 20/06/12. Only year could be 2 or 4 digits, rest will be same.

Any help will be highly appreciated.

Cheers,

4
  • Will date always be in dd/mm/yy format? Commented Apr 16, 2013 at 13:48
  • 1
    This question does not show any research effort. It is important to do your homework. Tell us what you found and why it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. FAQ. Commented Apr 16, 2013 at 13:50
  • @anubhava: please check my edit. Date will be in the same format except year could 2 or 4 digits. Commented Apr 16, 2013 at 13:52
  • @GhazanfarMir: Thanks, I answered it below, check it. Commented Apr 16, 2013 at 13:55

3 Answers 3

3

Use preg_replace like this:

$repl = preg_replace('~(\d{2})/(\d{2})/(\d{2,4})~', '$1-$2-$3', $str);

Live Demo: http://ideone.com/7HDNZa

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

Comments

0
$string = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{2,4})/", "$1-$2-$3", $string);

The regex will find 3 lots of 2 numbers (or 2x2 + 1x4) separated by /'s and replace them with the same numbers separated by -'s.

Comments

0

You could try something like this:

preg_replace('~\b([0-2]?[1-9]|3[01])/(0?[1-9]|1[0-2])/(?=(?:\d\d|\d{4})\b)~', '$1-$2-', $str);

Should match valid dates only. Does match dates where the prefix 0 is not present, e.g. 4/16/13 if this is not desierable, remove the two first question marks (in [0-2]? and 0?)

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.