Search & replace in files using php


Searching and replacing content in files is a common task all of us do regularly. Most programmers will implement it using Perl a shell script or through a editor. Perl offers itself as an excellent tool for the required purpose; we PHP programmers are not quite so lucky in that matter. Search/replace is easier from a shell prompt or an editor, but what if you have to do the same programatically in php. File_SearchReplace is a pear package that helps you search/replace in files through a nice object oriented interface.

Installation
Pear installation as usual is simple.

c:/> pear install File_SearchReplace

Doing a simple search & replace
The following is an simple example code that searches the file ‘fruits.txt’ and replaces all occurrences of ‘apples’ with ‘oranges’. The getNumOccurences function returns the total number of replaced strings in the file.

<?php
 
include 'File/SearchReplace.php' ;
 
$files_to_search = array("fruits.txt") ;
$search_string  = "apples";
$replace_string = "oranges";
 
$snr = new File_SearchReplace($search_string,
                              $replace_string,
                              $files_to_search,
                              '', // directorie(s) to search
                              false) ;
 
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
?>

The fourth option in the File_SearchReplace specifies a optional directory name to search. If the directory name is empty than the files will be searched in the current directory or in the respective path if a path is also included with the filename. Following is an example if you want to search all files in the directory ‘nature/fruits’.

<?php
 
include 'File/SearchReplace.php' ;
 
$files_to_search = array();
$direc_to_search = array('nature/fruits/');
 
$search_string  = "apples";
$replace_string = "oranges";
 
$snr = new File_SearchReplace($search_string,
                              $replace_string,
                              $files_to_search,
                              $direc_to_search, // directory to search
                              true) ; // 'true' to search subdirectories
 
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
?>

All the four starting options of File_SearchReplace are of mixed type; i.e they take a string or an array of strings as their options. For example in the following all occurrences of ‘apples’ will be replaced by ‘oranges’ and that of ‘pears’ by ‘grapes’.

<?php
 
include 'File/SearchReplace.php' ;
 
$files_to_search = array();
$direc_to_search = array('nature/fruits/');
 
$search_string  = array('apples', 'pears');
$replace_string = array('oranges', 'grapes');
 
$snr = new File_SearchReplace($search_string,
                              $replace_string,
                              $files_to_search,
                              $direc_to_search,
                              true) ;
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
?>

You don’t have to create a new instance everytime you need a new search, you can set the various parameters through the interface provided by the File_SearchReplace class as shown below.

<?php
 
include 'File/SearchReplace.php' ;
 
$files_to_search = array();
$direc_to_search = array('nature/fruits/');
 
$search_string  = array('apples', 'pears');
$replace_string = array('oranges', 'grapes');
 
$snr = new File_SearchReplace($search_string,
                              $replace_string,
                              $files_to_search,
                              $direc_to_search,
                              true) ;
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
/* Start a new search */
 
$snr->setFind( "oranges") ;
$snr->setReplace( "berries") ;
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
?>

Regular Expression search
You can also use a regular expression in a search string, but before that we must specify what kind of search is required with the ‘setSearchFunction’ as shown below. The following example replaces all occurrences of ‘color’ or ‘colour’ with the capital ‘COLOR’.

<?php
 
include 'File/SearchReplace.php' ;
 
$files_to_search = array();
$direc_to_search = array('test/graphics/');
 
$search_string  = '/col(o|ou)r/';
$replace_string = 'COLOR';
 
$snr = new File_SearchReplace($search_string,
                              $replace_string,
                              $files_to_search,
                              $direc_to_search,
                              true) ;
 
$snr->setSearchFunction("preg");
$snr->doSearch();
 
echo "The number of replaces done : " . $snr->getNumOccurences();
 
?>

The setSearchFunction takes one of the following four options:

normal – default
quick – use str_replace()
preg – use preg_replace()
ereg – use ereg_replace()

More information on this options can be found here.

In conclusion
The package can be quite useful when you want to replace large quantities of text programatically. As it works on plain strings and regular expressions, its can be quite a handy tool in many occasions.

This site is a digital habitat of Sameer Borate, a freelance web developer working in PHP, MySQL and WordPress. I also provide web scraping services, website design and development and integration of various Open Source API's. Contact me at metapix[at]gmail.com for any new project requirements and price quotes.

9 Responses

1

Sameer Borate’s Blog: Search & replace in files using php | Cole Design Studios

May 12th, 2009 at 11:11 am

[...] his blog today Sameer Borate has posted a quick tutorial on how to use a PEAR package to do search and replace on your files from inside of PHP. Searching [...]

2

Bookmarks for May 11th through May 14th « Relaxi

May 14th, 2009 at 1:57 pm

[...] Search & replace in files using php : CodeDiesel – [...]

3

kalaiselvi

June 3rd, 2009 at 12:23 pm

how to format a message in mail send part using php ?

4

devaraj

July 20th, 2009 at 9:23 pm

Your code is nice.But where is the include file.We cant able to execute your code.example
include ‘File/SearchReplace.php’ ;
where is the ‘File/SearchReplace.php’ file

sameer

July 20th, 2009 at 10:02 pm

The file is a PEAR library. You need to install it from the command line or download it from http://pear.php.net/package/File_SearchReplace/download

6

Kevin

May 7th, 2010 at 9:22 pm

http://php.net/manual/en/function.str-replace.php ( !!!) why would you not just use this instead? It comes with php!

7

eaposztrof

February 13th, 2013 at 5:54 am

great script, thank you!

there is any way to print the concerned filenames?

8

debain

February 16th, 2013 at 2:44 am

Thanks for this code! Good work.

I made this script work with FTP Files. Only thing to change is the writeout function. The Context for “overwrite” is missing.
See example here: http://forums.devnetwork.net/viewtopic.php?f=1&t=70062

Would be nice if you could include/change this!

9

KubiQ

March 8th, 2013 at 6:57 am

http://kubiq-design.wz.cz/qfind.zip

Copy PHP file to your parent directory and run it ;)

Your thoughts