我想用一个文本文件(例如:带有,H
的\nH
)中的另一个字符串替换某些字符串。有没有办法使用PHP实现这一点?
发布于 2009-09-17 20:32:05
您可以使用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);
?>
发布于 2009-09-17 12:32:28
有几个functions to read and write a file。
您可以使用file_get_contents
读取文件内容,使用str_replace
执行替换,然后使用file_put_contents
将修改后的数据放回原处
file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
发布于 2009-09-17 12:38:29
如果你使用的是Unix机器,你也可以通过php的program execution functions来使用sed。
因此,您不必通过php来传输文件的所有内容,并且可以使用正则表达式。可能会更快。
如果你不喜欢阅读手册页,你可以在Wikipedia上找到一个概述。
https://stackoverflow.com/questions/1438563
复制相似问题