【发布时间】:2016-06-15 11:07:08
【问题描述】:
我正在解析一个 .csv,其中包含一些格式为 Jan 10, 2015 的日期,我想将其转换为标准化日期 2015-01-10。
我做了一个函数,如果你输入非标准化日期Jan 10, 2015,输出标准化的日期:
function dateParser($dateVal)
{
$dateArray = date_parse($dateVal);
$parsedDate = sprintf("%04d-%02d-%02d", $dateArray["year"], $dateArray["month"], $dateArray["day"]);
return $parsedDate;
}
现在,我想做以下事情:
- 读取 .csv 文件
- 使用正则表达式查找日期
- 获取日期,调用
dateParser函数并在文件上替换 - 保存文件。
我该如何存档?
用Jan 10, 2015(或Jan 3, 2015)形式查找日期的正则表达式是\w+\s\d{1,2},\s\d{4}。这是我的代码:
// Get the content of the .csv file
$str = file_get_contents($csvFilePath);
// Of course this can't be done "on the go" so it's not working
$str = preg_replace('/\w+\s\d{1,2},\s\d{4}/', dateParser($HERE_I_WANT_TO_PUT_THE_REGEX_MATCH), $str);
// Save the output on the file
file_put_contents($csvFilePath, $str);
我怎样才能做到这一点? preg_replace 不允许我找到正则表达式并调用 dateParser 在旅途中。
编辑:所有的评论和答案都是关于数据转换的。我不需要数据转换方面的帮助,因为我的效果很好。我的问题是将正则表达式匹配和文件替换结合起来。
提前致谢!
【问题讨论】:
-
为什么不使用 date()?
Date("Y-m-d", strtotime($regexvalue)); -
@CBroe 如何在我的代码中使用它?我不明白这一点。谢谢!