php 如何使用php替换文本文件中的特定行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3004041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to replace a particular line in a text file using php?
提问by kishore
how to replace a particular row using php. I dont know the line number. I want to replace a line containing a particular word.
如何使用php替换特定行。我不知道行号。我想替换包含特定单词的行。
回答by gnarf
One approach that you can use on smaller files that can fit into your memory twice:
您可以在可以两次放入内存的较小文件上使用的一种方法:
$data = file('myfile'); // reads an array of lines
function replace_a_line($data) {
if (stristr($data, 'certain word')) {
return "replaement line!\n";
}
return $data;
}
$data = array_map('replace_a_line',$data);
file_put_contents('myfile', implode('', $data));
A quick note, PHP > 5.3.0 supports lambda functions so you can remove the named function declaration and shorten the map to:
快速说明,PHP > 5.3.0 支持 lambda 函数,因此您可以删除命名函数声明并将映射缩短为:
$data = array_map(function($data) {
return stristr($data,'certain word') ? "replacement line\n" : $data;
}, $data);
You could theoretically make this a single (harder to follow) php statement:
从理论上讲,您可以将其设为单个(更难遵循)的 php 语句:
file_put_contents('myfile', implode('',
array_map(function($data) {
return stristr($data,'certain word') ? "replacement line\n" : $data;
}, file('myfile'))
));
Another (less memory intensive) approach that you should use for larger files:
您应该用于较大文件的另一种(较少内存密集型)方法:
$reading = fopen('myfile', 'r');
$writing = fopen('myfile.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if (stristr($line,'certain word')) {
$line = "replacement line!\n";
$replaced = true;
}
fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('myfile.tmp', 'myfile');
} else {
unlink('myfile.tmp');
}
回答by Your Common Sense
You have to overwrite the entire file.
您必须覆盖整个文件。
So, for the relatively small file, read file into array, search for the word, replace found row, write all the restinto file.
因此,对于相对较小的文件,将文件读入数组,搜索单词,替换找到的行,将其余所有内容写入文件。
For the big file the algorithm is slightly different, but quite the same in general.
对于大文件,算法略有不同,但总体上完全相同。
Important part is file locking
重要的部分是文件锁定
that's why we prefer a database.
这就是我们更喜欢数据库的原因。
回答by Dan Heberden
You can also use multi-line mode with regular expressions
您还可以将多行模式与正则表达式一起使用
preg_match_all('/word}/m', $textfile, $matches);
this is, of course, assuming it's a smaller document at the ready and loaded. Otherwise, the other answers are far more 'real-world' of a solution.
当然,这是假设它是一个准备好并加载的较小文档。否则,其他答案更像是解决方案的“现实世界”。
回答by kb.
$filedata = file('filename');
$newdata = array();
$lookfor = 'replaceme';
$newtext = 'withme';
foreach ($filedata as $filerow) {
if (strstr($filerow, $lookfor) !== false)
$filerow = $newtext;
$newdata[] = $filerow;
}
Now $newdatacontains the file contents as an array (use implode()if you don't want array) with the line containing "replaceme" replaced with "withme".
现在$newdata将文件内容包含为一个数组(implode()如果您不想要数组,请使用),其中包含“replaceme”的行替换为“withme”。
回答by Gordon
If you don't know the line, you will have to search over all lines.
如果您不知道该行,则必须搜索所有行。
Either iterate over the file line by lineor read the file into memory all at once.
Then either find the word with a combination of strposand str_replaceor
use preg_replace.
无论是叠代由行的文件行或文件读入到内存中的所有一次。然后,要么找到的组合词strpos和str_replace或使用preg_replace。
If you iterate, simply use strposand replace the line once it didn't return FALSE. Then save the file back to disk.
如果您进行迭代,只需strpos在没有返回 FALSE 的情况下使用并替换该行。然后将文件保存回磁盘。
回答by ChickenFeet
This is good if you are looking for a substring (ID) in a line and want to replace the old line with the new one.
如果您要在一行中查找子字符串 (ID) 并希望用新行替换旧行,这很好。
Code:
代码:
$id = "123";
$new_line = "123,Programmer\r"; // We're not changing the ID, so ID 123 remains.
$contents = file_get_contents($dir);
$new_contents= "";
if( strpos($contents, $id) !== false) { // if file contains ID
$contents_array = preg_split("/\r\n|\r|\n/", $contents);
foreach ($contents_array as &$record) { // for each line
if (strpos($record, $id) !== false) { // if we have found the correct line
$new_contents .= $new_line; // change record to new record
}else{
$new_contents .= $record . "\r";
}
}
file_put_contents($dir, $new_contents); // save the records to the file
echo json_encode("Successfully updated record!");
}
else{
echo json_encode("failed - user ID ". $id ." doesn't exist!");
}
Example:
例子:
Old file:
旧文件:
ID,occupation
123,student
124,brick layer
身、职业
123,学生
124,砖层
Running the code will change file to:
运行代码会将文件更改为:
New file:
新文件:
ID,occupation
123,programmer
124,brick layer
身、职业
123,程序员
124,砖层
回答by DMVerfurth
You could turn the file into an array using the explode();function, edit any item in the array, use the implode();function to turn the array back into a string, then you can put the string back into the file using the file_put_contents();function. This is shown in the following function :
您可以使用该explode();函数将文件转换为数组,编辑数组中的任何项目,使用该implode();函数将数组转换回字符串,然后您可以使用该file_put_contents();函数将字符串重新放入文件中。这显示在以下函数中:
function file_edit_contents($file_name, $line, $new_value){
$file = explode("\n", rtrim(file_get_contents($file_name)));
$file[$line] = $new_value;
$file = implode("\n", $file);
file_put_contents($file_name, $file);
}
回答by Vasic Danijel
You can do like this:
你可以这样做:
$file = file('data.txt');
$data = 'new text';
$some_index = 2;
foreach($file as $index => $line){
if($index == $some_index){
$file[$index] = $data . "\n";
}
}
$content = implode($file);
file_put_contents('data.txt', $content);
回答by malik kurosaki
Maybe this could help:
也许这可以帮助:
$data = file("data.php");
for($i = 0;$i<count($data);$i++){
echo "<form action='index.php' method='post'>";
echo "<input type='text' value='$data[$i]' name='id[]'><br>";
}
echo "<input type='submit' value='simpan'>";
echo "</form>";
if(isset($_POST['id'])){
file_put_contents('data.php',implode("\n",$_POST['id'])) ;
}

