我有一个文件夹,里面装满了这样格式的文件......
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"比特不是必须的,但是因为它看起来不错,所以不会因此而受伤。
答案 0 :(得分:2)
修剪扩展。这假定它始终是.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 - 2017年6月30日
酒吧 - 2017年7月1日
如果您希望foo
和bar bar
大写,则可以使用ucwords()
等功能。
答案 1 :(得分:0)
在这里,我使用 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;
}