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?
+5
A:
You could read the entire file in with file_get_contents(), perform a str_replace(), and output it back with 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);
?>
Josh
2009-09-17 12:32:04
+2
A:
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_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
Gumbo
2009-09-17 12:32:27
Now the question really is: is your one-liner faster/more efficient than my three line version? ;-)
Josh
2009-09-17 12:36:09
A:
file_get_contents() then str_replace() and put back the modified string with file_put_contents() (pretty much what Josh said)
Mikey
2009-09-17 12:35:13
A:
If you're on a Unix machine, you could also use sed via php's program execution functions.
Thus, you do not have to pipe all of the file's content through php and can use regular expressions. Could be faster.
If you're not into reading manpages, you can find an overview on Wikipedia.
middus
2009-09-17 12:38:29