Search & replace in files using php


Posted in: libraries, pear, php | Save to del.icio.us | Twit This! 11 May 2009

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.




Share this post

Share on Facebook
Share on Twitter
Share on StumbleUpon
Share on Delicious
Share on Digg
Share on Technorati
Share on Reddit
Feeds RSS Subscribe to site Feed

Other related posts



5 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

Comment Form

Use the html <code> tag to insert small source code snippets

For longer code examples use http://pastie.org/.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

Recent Comments

  • sameer: You can try this in your templates header.php : http://pastie.org/867569 [...]
  • avanthi: I played it back by using selenium RC [...]
  • avanthi: Ohh, ok no problem, here the actual issue is with IE, when i play back in firefox it is working fine [...]
  • Veerendra: Hi sameer great plugin to filter content. I was searching this kind of filtering plugin for doing [...]
  • sameer: My apologies! I'm not conversant with SharePoint. [...]
  • avanthi: Is it possible to automate share point people picker control through selenium. When i record throug [...]
  • sameer: Check to see if the 'IDE > options > format' is set to HTML. [...]
  • sameer: Google strips any newline characters form the text. Although it does accept it with the online trans [...]

  • Users Online

    • 5 Users Online
    • 4 Guests, 1 Bot