WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Search and Replace Text : Searches Files for Specified Text and Replaces It by a Given Text
Categories : PHP, PHP Classes, Search, Filesystem Click here to Update Your Picture
MA Razzaque Rupom
Date : Jun 26th 2006
Grade : 3 of 5 (graded 3 times)
Viewed : 14744
File : 4432.zip
Images : No Images for this code example.
Search : More code by MA Razzaque Rupom
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

This code :
- Takes path to search files within
- Takes replacement key if you want to replace matching results by any text
- Traverses files within the directory( and subdirectories as well) specified
- Searches the specified search key within the files by regular expression
- Writes matched filename and number of occurences
- If replacementKey is given, it replaces the matched texts by the replacementKey using regular expression
- Writes results to a log file (if specified any) as well as standard display


TextSearch.class.php
<?php
/**
* Class : TextSearch
*
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource Group(http://groups.yahoo.com/group/phpresource/)
*             URL: http://www.rupom.info 
*       
* @version :  1.0
* Date     :  06/26/2006
* Purpose  :  Searching and replacing text within files of specified path
*/

class TextSearch
{     
     var
$extensions         = array();
     var
$searchKey          = '';     
     var
$replacementKey     = '';
     var
$caseSensitive      = 0; //by default case sensitivity is OFF
     
var $findAllExts        = 1; //by default all extensions
     
var $isReplacingEnabled = 0;
     var
$logString          = '';
     var
$errorText          = '';
     var
$totalFound         = 0; //total matches
     
   /**
   *   Sets extensions to look
   *   @param Array extensions
   *   @return none
   */   
   
function setExtensions($extensions = array())
   {
     
$this->extensions = $extensions;
     
      if(
sizeof($this->extensions))   
      {
         
$this->findAllExts = 0; //not all extensions
     
}
   }
//End of Method

   /**
   * Adds a search extension
   * @param  file extension
   * @return none
   */   
   
function addExtension($extension)
   {
     
     
array_push($this->extensions, $extension);     
     
$this->findAllExts = 0; //not all extensions
     
   
}//End of function

 
   /**
   * Sets search key and case sensitivity
   * @param search key, case sensitivity
   * @return none
   */   
   
function setSearchKey($searchKey, $caseSensitive = 0)
   {
     
$this->searchKey = $searchKey;
     
      if(
$caseSensitivity)
      {
         
$this->caseSensitive    = 1; //yeah, case sensitive
     
}
   }
//End of function

   /**
   *   Sets key to replace searchKey with
   *   @param : replacement key
   *   @return none
   */   
   
function setReplacementKey($replacementKey)
   {
   
     
$this->replacementKey     = $replacementKey;
     
$this->isReplacingEnabled = 1;   
   
   }
//End of function
   
   /**
   * Wrapper function around function findDirFiles()
   * @param $path to search
   * @return none
   */
   
function startSearching($path)
   {
     
$this->findDirFiles($path);     
   }
//EO Method
   
   /**
   * Recursively traverses files of a specified path
   * @param  path to execute
   * @return  none
   */   
   
function findDirFiles($path)
   {
     
$dir = opendir ($path);
     
      while (
$file = readdir ($dir))
      {
         if ((
$file == ".") or ($file == ".."))
         {
            continue;
         }               
                 
             if (
filetype ("$path/$file") == "dir")
             {                 
           
$this->findDirFiles("$path/$file"); //recursive traversing here
         
}                         
                 elseif(
$this->matchedExtension($file)) //checks extension if we need to search this file
                 
{                       
           if(
filesize("$path/$file"))
           {
               
$this->searchFileData("$path/$file"); //search file data               
           
}   
         }                   
      }
//End of while
     
     
closedir($dir);
         
   }
//EO Method

   /**
   * Finds extension of a file
   * @param filename
   * @return file extension
   */
   
function findExtension($file)
   {
       return
array_pop(explode(".",$file));
   }
//End of function
   
   /**
   * Checks if a file extension is one the extensions we are going to search
   * @param filename
   * @return true in success, false otherwise
   */   
   
function matchedExtension($file)
   {   
      if(
$this->findAllExts) //checks if all extensions are to be searched
     
{
         return
true;   
      }     
      elseif(
sizeof(array_keys($this->extensions, $this->findExtension($file)))==1)
      {
         return
true;   
      }
     
      return
false;       
   
   }
//EO Method
   
   /**
   * Searches data, replaces (if enabled) with given key, prepares log
   * @param $file
   * @return none
   */
   
function searchFileData($file)
   {
     
$searchKey  = preg_quote($this->searchKey);
     
      if(
$this->caseSensitive)
      {
         
$pattern    = "/$searchKey/U";
      }
      else
      {
           
$pattern    = "/$searchKey/Ui";
      }
     
     
$subject       = file_get_contents($file);
           
     
$found = 0;
           
     
$found = preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER);               
     
     
$this->totalFound +=$found;
                 
      if(
$found)
      {
           
$foundStr = "Found in $found places";
         
$this->appendToLog($file, $foundStr);
      }
     
       
      if(
$this->isReplacingEnabled && $this->replacementKey && $found)
      {           
         
$outputStr = preg_replace($pattern, $this->replacementKey, $subject);                                 
         
$foundStr = "Found in $found places";
         
$this->writeToFile($file, $outputStr);
         
$this->appendToLog($file, $foundStr, $this->replacementKey);
       
      }
      elseif(
$this->isReplacingEnabled && $this->replacementKey == '')
      {
         
$this->errorText .= "Replacement Text is not defined\n";
         
$this->appendToLog($file, "Replacement Text is not defined", $this->replacementKey);
      }
      elseif(!
found)
      {
         
$this->appendToLog($file, "No matching Found", $this->replacementKey);
      }
     
   }
//EO Method
   
   /**
   * Writes new data (after the replacement) to file
   * @param $file, $data
   * @return none
   */
   
function writeToFile($file, $data)
   {           
      if(
is_writable($file))
      {
         
$fp = fopen($file, "w");
         
fwrite($fp, $data);
         
fclose($fp);   
      }
      else
      {
         
$this->errorText .= "Can not replace text. File $file is not writable. \nPlease make it writable\n";   
      }
     
   }
//EO Method

   /**
   * Appends log data to previous log data
   * @param filename, match string, replacement key if any
   * @return none
   */   
   
function appendToLog($file, $matchStr, $replacementKey = null)
   {
         if(
$this->logString == '')
         {
           
$this->logString = " --- Searching for '".$this->searchKey."' --- \n";
         }
     
      if(
$replacementKey == null)
      {
         
$this->logString .= "Searching File $file : " . $matchStr."\n";           
      }
      else
      {
         
$this->logString .= "Searching File $file : " . $matchStr.". Replaced by '$replacementKey'\n";           
      }
     
   }
//EO Method
   
   /**
   * Shows Log
   * @param none
   * @return none
   */
   
function showLog()
   {
     
$this->dBug("------ Total ".$this->totalFound." Matches Found -----");
     
$this->dBug(nl2br($this->logString));             
     
      if(
$this->errorText!='')
      {
           
$this->dBug("------Error-----");
         
$this->dBug(nl2br($this->errorText));           
      }
   }
//EO Method
   
   /**
   * Writes log to file
   * @param log filename
   * @return none
   */
   
function writeLogToFile($file)
   {     
     
$fp = fopen($file, "wb") OR die("Can not open file <b>$file</b>");           
     
fwrite($fp, $this->logString);
     
fwrite($fp, "\n------ Total ".$this->totalFound." Matches Found -----\n");
      if(
$this->errorText!='')
      {
         
fwrite($fp, "\n------Error-----\n");     
         
fwrite($fp, $this->errorText);
      }
     
     
fclose($fp);     
   }
//EO Method
   
   /**
   * Dumps data
   * @param data to be dumped
   * @return none
   */
   
function dBug($dump)
   {
      echo
"<pre>";
     
print_r($dump);
      echo
"</pre>";     
   }
//EO Method
   
} //End of class

?>



Usage Example
<?php
/**
* Class : TextSearch
*
* @author  :  MA Razzaque Rupom <rupom_315@yahoo.com>, <rupom.bd@gmail.com>
*             Moderator, phpResource Group(LINK1http://groups.yahoo.com/group/phpresource/LINK1)
*             URL: LINK2http://www.rupom.infoLINK2 
*       
* @version :  1.0
* Date     :  06/26/2006
* Purpose  :  Searching and replacing text within files of specified path
*/

require_once('TextSearch.class.php');

$path = "/projects/phpResource/MyClasses"; //setting path to search
$logFile = "/projects/phpResource/MyClasses/SearchReplace/log_result.txt"; //setting log file

$obj = new TextSearch();
$obj->setExtensions(array('html','txt')); //setting extensions to search files within
$obj->addExtension('php');//adding an extension
$obj->setSearchKey(' PHP');
$obj->setReplacementKey('phpResource');//setting replacement text if you want to replace matches with that
$obj->startSearching($path);//starting search
$obj->showLog();//showing log
$obj->writeLogToFile($logFile); //writting result to log file

?>



Remote Archive (Zip, Tar, Gzip) downloader with FTP and local extration support
Categories : PHP, FTP, Filesystem, PHP Classes, Compression
filesplit : Split big text files in multiple small ones
Categories : PHP, Log Files, Filesystem, PHP Classes
A File Browser Class.To Read Drives,Directories and Files .Files writing is also possible
Categories : PHP, PHP Classes, Filesystem
Client classes for Dictionary servers UPDATED: 2000-06-06
Categories : Network, Search, Complete Programs, PHP Classes, PHP
Bs_IniHandler is a class that can read and write ini-style files (and strings)
Categories : PHP, Filesystem, PHP Classes
An efficient iterative and buffered text file reader
Categories : PHP, Classes and Objects, Filesystem, PHP Classes, Log Files
file class , uploade file , download file already uploaded on another website
Categories : PHP, PHP Classes, Filesystem, Web Services
Class that allows the PHP developer to create and manage UNIX like password files suitable for use as Apache authentication password files.
Categories : HTTP, PHP, PHP Classes, Filesystem
PHP Transfer data from text file to Mysql Table
Categories : PHP, PHP Classes, Filesystem, Databases, MySQL
Easy upload class
Categories : PHP Classes, Filesystem, HTTP, PHP
grab directory listings into an array the example prints out each subdirectory in the main dir - further work is to be performed on this one
Categories : Filesystem, PHP, Directories, Search, Utilities
Extended Get File List Function
Categories : PHP, Filesystem, Search, Directories
PHP4 DirectoryIterator Class
Categories : PHP, PHP Classes, Filesystem, Directories
Search for files
Categories : PHP, Filesystem, Search
Compare two texts and display a block of text with the differences between them.
Categories : PHP, PHP Classes, Filesystem, Strings, Arrays