2

I have string in following format 07_Dec_2010, I need to convert it to 07 Dec, 2010

How can I achieve following using single statement

3 Answers 3

3

If you are using PHP 5.3, you could also use the following to a) parse the date string and b) format it however you like:

$formatted = date_create_from_format('d_M_Y', '07_Dec_2010')->format('d M, Y');

(date_create_from_format() could also be DateTime::createFromFormat())

If you're not using 5.3 yet, you can use the following a) convert your string into a format that strtotime() understands, then b) format it however you like:

$formatted = date('d M, Y', strtotime(str_replace('_', '-', '07_Dec_2010')));

All that said, the other answers are fine if you just want to move portions of the string around.

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

Comments

1

You can do it using explode function as:

$dt = '07_Dec_2010';

list($d,$m,$y) = explode('_',$dt);    // split on underscore.
$dt_new = $d.' '.$m.','.$y;           // glue the pieces.

You can also do it using a single call to preg_replace as:

$dt_new = preg_replace(array('/_/','/_/'),array(' ',','),$dt,1);

Or also as:

$dt_new = preg_replace('/^([^_]*)_([^_]*)_(.*)$/',"$1 $2,$3",$dt);

Ideone link

1 Comment

I like your first one, very clean.
0
$new_date = preg_replace('/(\d+)_(\w+)_(\d+)/', '${1} ${2}, ${3}', $date);

Arrange ${1}, ${2}, ${3} as you like

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.