使用 PHP 在平面文件中查找和替换值 [英] find and replace values in a flat-file using PHP
问题描述
我认为已经有一个关于此的问题,但我找不到.也许解决方案太简单了......无论如何,我有一个平面文件并希望让用户根据名称更改值.我已经整理出使用 fopen('a')
模式创建新的名称+值对,使用 jQuery 发送带有 newValue
和 的 AJAX 调用新名称
.但是说内容看起来像这样:
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/
现在我想更改 folder
值.所以我将folder
作为oldName
和/tags/
作为newValue
发送.覆盖该值的最佳方法是什么?列表中的顺序无关紧要,名称将始终在左侧,后跟 |
(管道)、值和 new-line
.
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
.
我的第一个想法是读取列表,将其存储在一个数组中,在所有 [0]
中搜索 oldName
,然后更改 [1]
属于它,然后将其写回文件.但我觉得有更好的方法吗?有任何想法吗?也许 正则表达式?
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?
推荐答案
对整个文件使用 str_replace() 一个非常简单的方法:
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);
一次只能作为一个用户使用该文件.但是数据库总是一个更好的主意.如果您需要 CSV,最好有一个额外的 DB 到 CSV 脚本,而不仅仅是一个 CSV 文件.
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.
这篇关于使用 PHP 在平面文件中查找和替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!