Reputation: 15950
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
Upvotes: 2
Views: 1009
Reputation: 51950
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.
Upvotes: 3
Reputation: 455000
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);
Upvotes: 1
Reputation: 2200
$new_date = preg_replace('/(\d+)_(\w+)_(\d+)/', '${1} ${2}, ${3}', $date);
Arrange ${1}, ${2}, ${3} as you like
Upvotes: 0