【问题标题】:how can i replace some things in my array?我怎样才能替换我的阵列中的一些东西?
【发布时间】:2016-02-14 19:07:14
【问题描述】:

我需要在我的数组中格式化一个日期 - 但数组中的日期没有保存为数据库中的 datetime 或类似的东西.. 我已经从我的服务器中获取了日期并将它们删除.

所以我需要使用preg_replace 或str_replace

到目前为止我使用str_replace 所做的尝试:

    $reverse_date = str_replace( '[', '' ,$reverse_date);
    $reverse_date = str_replace( ']', '' ,$reverse_date);
    $reverse_date = str_replace( '/', '.' ,$reverse_date); 

但我不想为此使用三行代码。

如果我print_r这个,我会得到:12.Oct.2015:01:10:43 +0200

在它看起来像这样之前:[12/Oct/2015:00:37:29 +0200]

所以没关系!但是我还是不想用这三行,但是我不懂preg_replace的语法

我想要以下输出:

12.Oct.2015(space)01:10:43 +0200

【问题讨论】:

  • 是字符串还是数组
  • 它是一个数组!但我只需要数组的第一个数据,所以 $reverse_date[1]
  • 发布你的数组结构
  • 这是我的数组的 2 个日期:,"[12\/Oct\/2015:01:09:51 +0200]","[12\/Oct\/2015:01:08 :50 +0200]",
  • 请检查我的答案..

标签: php arrays replace


【解决方案1】:

使用date_parse拆开日期,将各部分组合成你需要的结果:

[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
// )

您没有将月份作为缩写字符串,但通过关联数组 (array(1 => 'Jan', ..., 12 => 'Dec')) 添加是微不足道的,而且您可以放心地处理日期解析内容和未来需求的变化。

【讨论】:

    【解决方案2】:

    正如您所说,您从以下格式的数组中获取日期

    [12/Oct/2015:00:37:29 +0200]
    

    所以不用str_replace或preg_replace,你可以简单地使用PHP的DateTime::createFromFormat函数,比如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
    

    Demo

    【讨论】:

    • 我收到此错误消息:此错误找不到类 'App\Http\Controllers\DateTime':$date = DateTime::createFromFormat("[d/M/Y:H:i :s P]","$reverse_date[1]"); echo $date->format('d.M.Y H:i:s P');
    • 你在使用 Laravel
    • 你在一个命名空间中,使用\DateTime::create...
    【解决方案3】:

    好的,我发现了如何在一行中使用 preg_replace 来做到这一点,但是我更喜欢 Uchiha 使用日期格式的答案——即使他没有使用正则表达式,这可能是最好的方法。

    echo preg_replace(['~(?<=\d{4}:\d{2}):~', '~[\[]~', '~[\]]~', '~[\/]~g'],[' ', '', '', '.'],'[12/Oct/2015:00:37:29 +0200]');
    

    12.Oct.2015:00 37:29 +0200

    【讨论】:

    • 它不会用空格替换第一个冒号
    • 冒号加空格?在哪里
    • “我想要以下输出:12.Oct.2015(space)01:10:43 +0200” - 问题的最后两行
    • 哦,好吧,我明白你的意思了
    • 看看这个 - 已修复
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    • 2011-01-31
    • 2023-01-22
    • 2021-07-12
    相关资源
    最近更新 更多