Find and replace values ​​in a flat file using PHP

I think that this question already had a question, but I can not find it. Maybe the solution is too simple ... Anyway, I have a flat file and you want the user to change values ​​based on the name. I already sorted the creation of a new name + value pair using mode fopen('a'), using jQuery to send an AJAX call with newValueand newName. But let's say that the content is as follows:

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

And now I want to change the value folder. Therefore, I will post in folderhow oldNameand /tags/how newValue. What is the best way to rewrite meaning? The order in the list does not matter, and the name will always be on the left, and then |(pipe), value, and then new-line.

My first thought was to read the list, save it in an array, find everything [0]for oldName, and then change [1]which belongs to it, and then write it back to the file. But I feel there is a better way around this? Any ideas? Perhaps regex ?

+3
source share
2 answers

A very simple way: use str_replace () for 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);

This should only work as one user at a time. But a database is always a better idea. If you need a CSV, it is better to have an extra database for the CSV script than just a CSV file.

+9
source

PHP, APC, . , , .

, CSV, , . RDMS (MySQL), SQLite. , (UPDATE), , CSV , concurrency.

, , sed awk, . , , (s///), ,

+5

Source: https://habr.com/ru/post/1747853/


All Articles