Reputation: 169
I need to format a date in my array - but the date in the array isn't saved as a datetime
in a database or something like this.. I've got the dates from my server with cut them out.
So I need to work with preg_replace
or with str_replace
What I've tried so far using str_replace
:
$reverse_date = str_replace( '[', '' ,$reverse_date);
$reverse_date = str_replace( ']', '' ,$reverse_date);
$reverse_date = str_replace( '/', '.' ,$reverse_date);
but I don't want to use three lines for this.
If I print_r
this, I will get : 12.Oct.2015:01:10:43 +0200
before it was looking like this : [12/Oct/2015:00:37:29 +0200]
so this is okay ! But I still don't want to use three lines for this, but I don't understand the preg_replace
syntax
I want the following output :
12.Oct.2015(space)01:10:43 +0200
Upvotes: 3
Views: 143
Reputation: 18840
Ok I found out how to do it with preg_replace in one line, however I like the Uchiha answer with the date format more - even that he is not using the regex, this is probably the best way to go.
echo preg_replace(['~(?<=\d{4}:\d{2}):~', '~[\[]~', '~[\]]~', '~[\/]~g'],[' ', '', '', '.'],'[12/Oct/2015:00:37:29 +0200]');
12.Oct.2015:00 37:29 +0200
Upvotes: 0
Reputation: 21437
As you have said you were getting a date from an array within the following format
[12/Oct/2015:00:37:29 +0200]
So instead of using str_replace
or preg_replace
you can simply use DateTime::createFromFormat
function of PHP like as
$date = DateTime::createFromFormat("[d/M/Y:H:i:s P]","[12/Oct/2015:00:37:29 +0200]");
echo $date->format('d.M.Y H:i:s P');//12.Oct.2015 00:37:29 +02:00
Upvotes: 3
Reputation:
Use date_parse
to disassemble the date and combine the parts to form your needed result:
[40] boris> $date_array = date_parse(" [12/Oct/2015:00:37:29 +0200] ");
// array(
// 'year' => 2015,
// 'month' => 10,
// 'day' => 12,
// 'hour' => 0,
// 'minute' => 37,
// 'second' => 29,
// 'fraction' => 0,
// 'warning_count' => 0,
// 'warnings' => array(
//
// ),
// 'error_count' => 2,
// 'errors' => array(
// 0 => 'Unexpected character',
// 27 => 'Unexpected character'
// ),
// 'is_localtime' => true,
// 'zone_type' => 1,
// 'zone' => -120,
// 'is_dst' => false
// )
You don't have the month as abbreviated string, but that is trivial to add via an associative array (array(1 => 'Jan', ..., 12 => 'Dec')
), and you are on the safe side concerning the date-parsing stuff and future changes in your needs.
Upvotes: 1