将日期格式 YYYY-MM-DD-HH-MM-SS 替换为格式化日期

Replace Date Format YYYY-MM-DD-HH-MM-SS Into Formatted Date

我有一个文件夹,里面装满了格式如下的文件...

2017-06-30-18-21-52 foo.txt
2017-07-01-19-06-21 bar bar.txt

所需的回显输出为:

"Foo" -- June 30th, 2017
"Bar Bar" -- July 7th, 2017

"th" 和 "rd" 位并不是绝对必要的,但问问也无妨,因为它看起来很漂亮。

Trim分机走了。这假设它总是 .txt 而不是别的。然后你通过在空格上展开来得到日期,得到第一个值 - 这是日期 - 取消设置它,这样当你用 implode() 将它粘回去时,它不包括在内。

因为 2017-06-30-18-21-52 不是传递给 DateTime 构造函数的有效格式,我们使用 DateTime::createFromFormat().

$array = array();
$array[] = "2017-06-30-18-21-52 foo.txt";
$array[] = "2017-07-01-19-06-21 bar bar.txt";

foreach ($array as $v) {
    $v = rtrim($v, ".txt");
    $boom = explode(" ", $v);   // Separate the date 
    $date = DateTime::createFromFormat("Y-m-d-H-i-s", $boom[0]);
    unset($boom[0]);             // Unset the date
    $text = implode(" ", $boom);

    echo $text." -- ".$date->format("F jS, Y")."\n";
}

输出:

foo -- June 30th, 2017
bar bar -- July 1st, 2017

如果你想让foobar bar大写,你可以使用ucwords().

这样的函数

Live demo

这里我使用 Regex 从这些格式中提取数据。

<?php
$files = [
    "2017-06-30-18-21-52 foo.txt",
    "2017-07-01-19-06-21 bar bar.txt"
];

foreach ($files as $file) {
    echo format($file), PHP_EOL;
}

function format($file) {
    $result = "";
    $match  = [];
    $assert = preg_match("/^([0-9]{4}-[0-9]{2}-[0-9]{2})-([0-9]{2}-[0-9]{2}-[0-9]{2}) ([a-zA-z ]*)/is", $file, $match);
    if ($assert== true) {
       $date   = \DateTime::createFromFormat("Y-m-d", $match[1]);
       $result = ucwords($match[3]) . " -- " . $date->format("F jS, Y");
    } else {
       $result = $file;
    }

    return $result;
}