查找并在文件中替换(Find and replace in a file)

2019-07-18 09:11发布

我想用另一个文本文件来替换某些字符串(例如: \nH,H )。 有没有什么办法,使用PHP?

Answer 1:

你可以阅读与整个文件的file_get_contents() ,执行str_replace()函数 ,并与输出回file_put_contents() 。

示例代码:

<?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);

?>


Answer 2:

有几个功能,读取和写入文件 。

你可以阅读文件的内容用file_get_contents ,执行与替代str_replace ,并把修改后的数据回来file_put_contents

file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));


Answer 3:

如果您使用的是UNIX的机器上,你也可以使用的sed通过PHP的程序执行的功能 。

因此,你不必管文件的所有内容通过PHP,可以使用正则表达式。 可能会更快。

如果你不进入阅读手册页,你可以找到一个概述维基百科 。



Answer 4:

file_get_contents() ,然后str_replace() ,并把回来的修改后的字符串file_put_contents()差不多就是乔希说)



文章来源: Find and replace in a file
标签: php replace