在文件中查找字符串并将其替换为php

时间:2016-06-15 11:07:09

标签: php regex date

我正在解析一个.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. 保存文件。
  5. 我怎么能达到这个目的?

    使用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

    编辑:所有的答案和答案都与数据转换有关。我不需要数据转换的帮助,因为我的工作很棒。我的问题是将正则表达式匹配和替换文件组合在一起。

    提前致谢!

1 个答案:

答案 0 :(得分:3)

为什么不使用DateTime课程来转换日期?

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

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

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

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

e.g。

$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);