Search code examples
phpregexreplaceflat-file

find and replace values in a flat-file using PHP


I'd think there was a question on this already, but I can't find one. Maybe the solution is too easy... Anyway, I have a flat-file and want to let the user change the values based on a name. I've already sorted out creating new name+value-pairs using the fopen('a') mode, using jQuery to send the AJAX call with newValue and newName. But say the content looks like this:

host|http:www.stackoverflow.com
folder|/questions/
folder2|/users/

And now I want to change the folder value. So I'll send in folder as oldName and /tags/ as newValue. What's the best way to overwrite the value? The order in the list doesn't matter, and the name will always be on the left, followed by a |(pipe), the value and then a new-line.

My first thought was to read the list, store it in an array, search all the [0]'s for oldName, then change the [1] that belongs to it, and then write it back to a file. But I feel there is a better way around this? Any ideas? Maybe regex?


Solution

  • A very easy way would it be to use str_replace() on the whole file:

    // read the file
    $file = file_get_contents('filename.csv');
    // replace the data
    $file = str_replace('folder|oldValue', 'folder|newValue', $file);
    // write the file
    file_put_contents('filename.csv', $file);
    

    That should work as only one user the file at a time. But a database is always a better idea. If you need CSV, it's better to have an additional DB to CSV script than only a CSV file.