php 在文件中查找和替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1438563/
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
Find and replace in a file
提问by ArK
I want to replace certain strings with another one in a text file(ex: \nHwith ,H). Is there any way to that using PHP?
我想用文本文件中的另一个字符串替换某些字符串(例如:\nHwith ,H)。有没有办法使用PHP?
回答by Josh
You could read the entire file in with file_get_contents(), perform a str_replace(), and output it back with file_put_contents().
您可以使用file_get_contents()读取整个文件,执行str_replace(),然后使用file_put_contents() 将其输出。
Sample code:
示例代码:
<?php
$path_to_file = 'path/to/the/file';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH",",H",$file_contents);
file_put_contents($path_to_file,$file_contents);
?>
回答by Gumbo
There are several functions to read and write a file.
有几个函数可以读取和写入文件。
You can read the file's content with file_get_contents, perform the replace with str_replaceand put the modified data back with file_put_contents:
您可以使用 读取文件的内容file_get_contents,执行替换str_replace并将修改后的数据放回file_put_contents:
file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
回答by middus
If you're on a Unix machine, you could also use sedvia php's program execution functions.
如果您使用的是 Unix 机器,您还可以通过 php 的程序执行函数使用sed。
Thus, you do not have to pipe all of the file's content through php and can use regular expressions. Could be faster.
因此,您不必通过 php 传输文件的所有内容,而可以使用正则表达式。可以更快。
If you're not into reading manpages, you can find an overview on Wikipedia.
如果您不喜欢阅读联机帮助页,可以在Wikipedia上找到概述。
回答by Mikey
file_get_contents()then str_replace()and put back the modified string with file_put_contents()(pretty much what Josh said)
file_get_contents()然后str_replace()放回修改后的字符串file_put_contents()(几乎是乔希所说的)

