我想在文本文件中将某些字符串替换为另一个字符串(例如,\nH
替换为 ,H
)。是否有使用 PHP 进行此操作的方法?
<?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);
?>
有几个用于读写文件的函数。
你可以使用file_get_contents
读取文件内容,使用str_replace
执行替换操作,再使用file_put_contents
将修改后的数据写回:
file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
.env
文件中的db设置(用于docker或travis等)。这对于这种情况看起来非常不错。 - Yegafile_get_contents()
然后使用 str_replace()
进行替换,最后使用 file_put_contents()
将修改后的字符串写回文件中(基本上就是 Josh 说的)