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 Labview机器人问题
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr