Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace in a file

Tags:

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?

like image 514
ArK Avatar asked Sep 17 '09 12:09

ArK


People also ask

Can you find and replace in a text file?

Open the text file in Notepad. Click Edit on the menu bar, then select Replace in the Edit menu. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement. See our using search and replace and advanced options section for further information and help.

How do I find and replace text in multiple files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

What is the command for search and replace?

You can also open the basic Find and Replace pane with the keyboard shortcut CONTROL + H.


1 Answers

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);  ?> 
like image 83
Josh Avatar answered Sep 22 '22 02:09

Josh