简体   繁体   中英

Finding a string in file and replacing in it php

I'm parsing a .csv that contains some dates with the format Jan 10, 2015 which I want to convert to a normalized date 2015-01-10 .

I made a function that if you enter the non-normalized date Jan 10, 2015 , outputs the normalized one:

function dateParser($dateVal)
{
    $dateArray = date_parse($dateVal);
    $parsedDate = sprintf("%04d-%02d-%02d", $dateArray["year"], $dateArray["month"], $dateArray["day"]);
    return $parsedDate;
}

Now, I want to do the following:

  1. Read the .csv file
  2. Find with regex the dates
  3. Get the date, call to the dateParser function and replace it on the file
  4. Save the file.

How can I archieve this?

The regex to find a date with the form Jan 10, 2015 (or Jan 3, 2015 ) is \\w+\\s\\d{1,2},\\s\\d{4} . And this is my code:

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

How can I make this? The preg_replace doesn't allow me to find the regex and call the dateParser on the go .

EDIT: All the coments and the answer are about the data convertion. I dont need help with the data convertion as mine works great. My problem is to combine the regex match and the replacement on the file.

Thanks in advance!

Why not use the DateTime class to convert your dates?

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

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

This should accept all date formats and convert it to the correct format.

To replace all the dates within the file you could use the preg_match_all and str_replace functions.

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM