如何在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.

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/

With the help of regex you can do this. In pattern create capture group for garbing year, months, days, hours, minutes and seconds. Simple example:

$str = "20142311.235504";
preg_match('~^(?<year>\d{4})(?<day>\d{2})(?<month>\d{2}).(?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})$~', $str, $match);

echo '<pre>', print_r($match);

But I prepare you to use date_create_from_format() which is more easier and faster than regex. First, convert a known date format separated by -, explode that format to convert an array and finally assign the array to a set of key [by array_combine()]. Example:

$str = "20142311.235504";
$match = array_combine(['year', 'month', 'day', 'hour', 'minute', 'second'], explode('-', (date_create_from_format("Ydm.His", $str))->format('Y-m-d-H-i-s')));
echo '<pre>', print_r($match);