【问题标题】:Finding a string in file and replacing in it php在文件中查找字符串并在其中替换 php
【发布时间】: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;
}

现在,我想做以下事情:

  1. 读取 .csv 文件
  2. 使用正则表达式查找日期
  3. 获取日期,调用dateParser函数并在文件上替换
  4. 保存文件。

我该如何存档?

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 在旅途中

编辑:所有的评论和答案都是关于数据转换的。我不需要数据转换方面的帮助,因为我的效果很好。我的问题是将正则表达式匹配和文件替换结合起来。

提前致谢!

【问题讨论】:

标签: php regex date


【解决方案1】:

为什么不使用DateTime 类来转换您的日期?

$date = date_create("Jan 10, 2015");
$formattedDate = $date->format('Y-m-d');

echo $formattedDate; //Outputs 2015-01-10

这应该接受所有日期格式并将其转换为正确的格式。

要替换文件中的所有日期,您可以使用 preg_match_allstr_replace 函数。

例如

$str = file_get_contents($csvFilePath);
$regex = '/\w+\s\d{1,2},\s\d{4}/';

//Search the file for dates that match the regex
preg_match_all($regex, $str, $matches);

//Replace each value that matches the regex
foreach ($matches[0] as $m) {
    $date = date_create($m);
    $formattedDate = $date->format('Y-m-d');

    $str = str_replace($m, $formattedDate, $str);
}

file_put_contents($csvFilePath, $str);

【讨论】:

  • 这不是我真正的问题,我的日期转换也有效。正如您在帖子中看到的那样,我需要先使用正则表达式来搜索日期,然后对其进行转换(按照我发布的方式或您的方式,我不在乎),然后在文件中替换它。
  • @Borja,编辑了我的答案...如果可行,请告诉我
  • 谢谢。我收到错误 date_create() expects parameter 1 to be string, array given 因为 $matchesarray(1) { [0]=> array(116) { [0]=> string(12) "May 22, 2015" [1]=> string(12) "Feb 27, 2015" [2] etcetc (它似乎里面有两个数组,对吧?
  • 如您所说,我正在使用date_create($m)。这是$matches pastebin.com/SShDU96M 的内容。如您所见,它是一个多维数组,因此 foreach 的第一次迭代(又名$m 的第一个值)是一个包含字符串本身的数组。
  • 太棒了!很高兴我能帮上忙。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
相关资源
最近更新 更多