I want to replace certain strings with another one in a text file (ex: \nH
with ,H
). Is there any way to that using PHP?
我想用文本文件中的另一个字符串替换某些字符串(例如:\ nH with,H)。有没有办法使用PHP?
4 个解决方案
#1
43
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);
?>
#2
12
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_replace
and 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)));
#3
9
If you're on a Unix machine, you could also use sed via 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.
如果您没有阅读联机帮助页,可以在*上找到概述。
#4
1
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()放回修改后的字符串(几乎就是Josh所说的)
#1
43
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);
?>
#2
12
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_replace
and 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)));
#3
9
If you're on a Unix machine, you could also use sed via 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.
如果您没有阅读联机帮助页,可以在*上找到概述。
#4
1
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()放回修改后的字符串(几乎就是Josh所说的)