drddx3115 2019-07-24 07:41
浏览 63
已采纳

如何在php中以所需的格式拆分字符串

I've a string like below

$num = "20142311.235504";

I want to split the string in below format

$date['year'] = 2014;
$date['Month'] = 23;
$date['day'] = 11;
$date['hour'] = 23;
$date['min'] = 55;
$date['sec'] = 04;

or even in date form like below

2014/23/11 23:55:04

I tried using preg_split('/(d{4})/',$num,$matches); and str_split but am not getting the desired output. Your help is highly appreciated.

  • 写回答

2条回答 默认 最新

  • duanlu1922 2019-07-24 07:51
    关注

    If the string is a date, you can do this :

    $num = "20142311.235504";
    
    // You create a date with your string according to your current format
    $date = date_create_from_format("Ydm.His", $num);
    
    // Now you can play with it
    $formattedDate = $date->format("Y/d/m H:i:s"); // `string(19) "2014/23/11 23:55:04"` 
    
    $dateTest['year']  = $date->format("Y"); // 2014
    $dateTest['Month'] = $date->format("m"); // 11
    $dateTest['day']   = $date->format("d"); // 23
    $dateTest['hour']  = $date->format("H"); // 23
    $dateTest['min']   = $date->format("i"); // 55
    $dateTest['sec']   = $date->format("s"); // 04
    
    

    Demo here : http://sandbox.onlinephpfunctions.com/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画