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