【问题标题】:Update time format using implode and explode使用 implode 和 explode 更新时间格式
【发布时间】:2015-07-30 20:53:01
【问题描述】:

我有如下字符串

12:00:00,11:30:00,10:30:00,10:00:00,09:30:00

我需要将其转换为

12:00,11:30,10:30,10:00,09:30

单个值可以通过使用转换

date('H:i',strtotime(explode(',',$req->slots)[0]))

有没有什么方法可以在不重复它们的情况下简单地做到这一点?

【问题讨论】:

  • 是单个字符串还是字符串数组?
  • @splash58 : 单个字符串
  • 如果你经常这样做 仅供参考:) - eval.in/409238

标签: php date explode strtotime implode


【解决方案1】:

你可以正则表达式。

echo preg_replace('~:\d{2}(,|$)~', '$1', '12:00:00,11:30:00,10:30:00,10:00:00,09:30:00');

输出:

12:00,11:30,10:30,10:00,09:30

正则表达式演示:https://regex101.com/r/vW0kN4/2
PHP 演示:http://sandbox.onlinephpfunctions.com/code/91d3f2ceb8c7f763e51c32841c4ee201070ab514

【讨论】:

  • 这就是我要找的东西
【解决方案2】:
$str = '12:00:00,11:30:00,10:30:00,10:00:00,09:30:00';
$ar = explode(',', $str);

foreach($ar as &$item) 
   $item = substr($item, 0,-3);

echo $str = implode(',', $ar); // 12:00,11:30,10:30,10:00,09:30

【讨论】:

    【解决方案3】:
    $result = array();
    foreach(explode(',', $req->slots) as $time) $result[] = date('H:i',strtotime($time));
    $result = implode(',', $result);
    

    【讨论】:

      【解决方案4】:

      嗯...它有点不迭代:

       var str = "12:00:00,11:30:00,10:30:00,10:00:00,09:30:00";
       var new_str = str.split(",").map(function(x){return x.replace(/^(.*):.*$/, "$1")}).join(",");
      

      JSFiddle: http://jsfiddle.net/trex005/9kdcaowf/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        • 2018-06-21
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 2016-01-01
        • 2020-02-03
        相关资源
        最近更新 更多