Search Code
  Home arrow Search Code arrow Search and Replace class
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
SEARCH CODE

Search and Replace class
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2002-04-26

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Class to enable search/replace of files. Can perform the search over one file, multiple files, entire directories with/without subdirectories. Can search using four different search functions, supporting ereg and preg regular expressions. Website

    By : Matt

    <?php
    /***************************************
    ** Title........: Search and replace utility
    ** Filename.....: search.replace.php
    ** Author.......: Richard Heyes
    ** Version......: 1.0
    ** Notes........:
    ** Last changed.: 09/09/2000
    ** Last change..:
    ***************************************/

    class search_replace{

    var $find;
    var $replace;
    var $files;
    var $directories;
    var $include_subdir;
    var $ignore_lines;
    var $ignore_sep;
    var $occurences;
    var $search_function;
    var $last_error;

    /***************************************
    ** Constructor function. Sets up the
    ** above functions.
    ***************************************/
    function search_replace($find, $replace, $files, $directories = '', $include_subdir = 1, $ignore_lines = array()){

    $this->find = $find;
    $this->replace = $replace;
    $this->files = $files;
    $this->directories = $directories;
    $this->include_subdir = $include_subdir;
    $this->ignore_lines = $ignore_lines;

    $this->occurences = 0;
    $this->search_function = 'search';
    $this->last_error = '';

    }

    /***************************************
    ** Accessor for retrieving occurences.
    ***************************************/
    function get_num_occurences(){
    return $this->occurences;
    }

    /***************************************
    ** Accessor for retrieving last error.
    ***************************************/
    function get_last_error(){
    return $this->last_error;
    }

    /***************************************
    ** Accessor for setting find variable.
    ***************************************/
    function set_find($find){
    $this->find = $find;
    }

    /***************************************
    ** Accessor for setting replace variable.
    ***************************************/
    function set_replace($replace){
    $this->replace = $replace;
    }

    /***************************************
    ** Accessor for setting files variable.
    ***************************************/
    function set_files($files){
    $this->files = $files;
    }

    /***************************************
    ** Accessor for setting directories variable.
    ***************************************/
    function set_directories($directories){
    $this->directories = $directories;
    }

    /***************************************
    ** Accessor for setting include_subdir variable.
    ***************************************/
    function set_include_subdir($include_subdir){
    $this->include_subdir = $include_subdir;
    }

    /***************************************
    ** Accessor for setting ignore_lines variable.
    ***************************************/
    function set_ignore_lines($ignore_lines){
    $this->ignore_lines = $ignore_lines;
    }

    /***************************************
    ** Function to determine which search
    ** function is used.
    ***************************************/
    function set_search_function($search_function){
    switch($search_function){
    case 'normal': $this->search_function = 'search';
    return TRUE;
    break;

    case 'quick' : $this->search_function = 'quick_search';
    return TRUE;
    break;

    case 'preg' : $this->search_function = 'preg_search';
    return TRUE;
    break;

    case 'ereg' : $this->search_function = 'ereg_search';
    return TRUE;
    break;

    default : $this->last_error = 'Invalid search function specified';
    return FALSE;
    break;
    }
    }


    /***************************************
    ** The main search and replace routine.
    ** Private function - DO NOT CALL!
    ***************************************/
    function search($filename){

    $occurences = 0;
    $file_array = file($filename);

    for($i=0; $i<count($file_array); $i++){

    if(count($this->ignore_lines) > 0){
    for($j=0; $j<count($this->ignore_lines); $j++){
    if(substr($file_array[$i],0,strlen($this->ignore_lines[$j])) == $this->ignore_lines[$j]) continue 2;
    }
    }

    $occurences += count(explode($this->find, $file_array[$i])) - 1;
    $file_array[$i] = str_replace($this->find, $this->replace, $file_array[$i]);
    }
    if($occurences > 0) $return = array($occurences, implode('', $file_array)); else $return = FALSE;
    return $return;

    }

    /***************************************
    ** The quick search function. Does not
    ** support the ignore_lines feature.
    ***************************************/
    function quick_search($filename){

    clearstatcache();

    $file = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);
    $occurences = count(explode($this->find, $file)) - 1;
    $file = str_replace($this->find, $this->replace, $file);

    if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
    return $return;

    }

    /***************************************
    ** The preg search function. Does not
    ** support the ignore_lines feature.
    ***************************************/
    function preg_search($filename){

    clearstatcache();

    $file = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);
    $occurences = count($matches = preg_split($this->find, $file)) - 1;
    $file = preg_replace($this->find, $this->replace, $file);

    if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
    return $return;

    }

    /***************************************
    ** The ereg search function. Does not
    ** support the ignore_lines feature.
    ***************************************/
    function ereg_search($filename){

    clearstatcache();

    $file = fread($fp = fopen($filename, 'r'), filesize($filename)); fclose($fp);

    $occurences = count($matches = split($this->find, $file)) -1;
    $file = ereg_replace($this->find, $this->replace, $file);

    if($occurences > 0) $return = array($occurences, $file); else $return = FALSE;
    return $return;

    }

    /***************************************
    ** Function for writing out a new file.
    ***************************************/
    function writeout($filename, $contents){

    if($fp = @fopen($filename, 'w')){
    flock($fp,2);
    fwrite($fp, $contents);
    flock($fp,3);
    fclose($fp);
    }else{
    $this->last_error = 'Could not open file: '.$filename;
    }

    }

    /***************************************
    ** Internal function called by do_search()
    ** to sort out any files that need searching.
    ***************************************/
    function do_files($ser_func){
    if(!is_array($this->files)) $this->files = explode(',', $this->files);
    for($i=0; $i<count($this->files); $i++){
    if($this->files[$i] == '.' OR $this->files[$i] == '..') continue;
    if(is_dir($this->files[$i]) == TRUE) continue;
    $newfile = $this->$ser_func($this->files[$i]);
    if(is_array($newfile) == TRUE){
    $this->writeout($this->files[$i], $newfile[1]);
    $this->occurences += $newfile[0];
    }
    }
    }

    /***************************************
    ** Internal function called by do_search()
    ** to sort out any dirs that need searching.
    ***************************************/
    function do_directories($ser_func){
    if(!is_array($this->directories)) $this->directories = explode(',', $this->directories);
    for($i=0; $i<count($this->directories); $i++){
    $dh = opendir($this->directories[$i]);
    while($file = readdir($dh)){
    if($file == '.' OR $file == '..') continue;

    if(is_dir($this->directories[$i].$file) == TRUE){
    if($this->include_subdir == 1){
    $this->directories[] = $this->directories[$i].$file.'/';
    continue;
    }else{
    continue;
    }
    }

    $newfile = $this->$ser_func($this->directories[$i].$file);
    if(is_array($newfile) == TRUE){
    $this->writeout($this->directories[$i].$file, $newfile[1]);
    $this->occurences += $newfile[0];
    }
    }
    }
    }

    /***************************************
    ** This starts the search/replace off.
    ** Call this to do the search.
    ** First do whatever files are specified,
    ** and/or if directories are specified,
    ** do those too.
    ***************************************/
    function do_search(){
    if($this->find != ''){
    if((is_array($this->files) AND count($this->files) > 0) OR $this->files != '') $this->do_files($this->search_function);
    if($this->directories != '') $this->do_directories($this->search_function);
    }
    }

    } // End of class
    ?>

    <?php
    /***************************************
    ** Title........: Search and Replace class
    ** Filename.....: example.php
    ** Author.......: Richard Heyes
    ** Version......: See script
    ** Notes........:
    ** Last changed.: 10/09/2000
    ** Last change..:
    ***************************************/

    include('class.search_replace.inc');

    /***************************************
    ** Create the object, set the search
    ** function and run it. Then change the
    ** pattern to find something else, and
    ** re-run the search.
    ***************************************/

    $sr = new file_search_replace('test', 'Replaced!', array('test.txt'), '', 1, array('##'));

    /***************************************
    ** Following function not necessary as
    ** normal is the default, but here to
    ** illustrate it.
    ***************************************/
    $sr->set_search_function('normal');

    $sr->do_search();
    $sr->set_find('another');
    $sr->do_search();

    /***************************************
    ** Some ouput purely for the example.
    ***************************************/
    header('Content-Type: text/plain');
    echo 'Number of occurences found: '.$sr->get_num_occurences()."\r\n";
    echo 'Error message.............: '.$sr->get_last_error()."\r\n";

    ?>

    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Search Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Best Practices in Integrated Requirements Management

    Poor Requirements Management capabilities in an Enterprise have been linked to excessive project failures, escalating IT costs, and failure to deliver competitive advantage into the marketplace. Join Brianna M Smith from IBM Rational and learn about how successful organizations align IT and Business stakeholders through collaborative processes and tools for effective requirements management, and how an integrated approach across the IT lifecycle can provide unparalleled visibility and traceability to ensure that project teams are delivering on the business vision by "doing the right things" and "doing things right."
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Hacking 101

    Join us for this web seminar to learn how you can defend your web applications from attack. Learn about the 3 most common web application attacks, including how they occur and what can be done to prevent them. We’ll also discuss manual versus automated approaches for scanning and identifying web application vulnerabilities and how IBM Rational AppScan, an automated vulnerability scanner, can help you automate more of what you are doing manually today.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Successful Change and Release Management for .NET

    Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! The dirty dozen: preventing common application-level hack attacks

    As organizations have grown increasingly dependent on online software, the risk of malicious attacks has also become far more serious. Fortunately, well-governed organizations can protect their Web applications by injecting vulnerability assessments and ethical hacks into their software development and delivery processes. This paper describes 12 of the most common hacker attacks and provides basic rules that you can follow to help create more hack-resistant Web applications.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Understanding Web application security challenges

    As businesses grow increasingly dependent upon Web applications, these complex entities grow more difficult to secure. Most companies equip their Web sites with firewalls, Secure Sockets Layer (SSL), and network and host security, but the majority of attacks are on applications themselves – and these technologies cannot prevent them. This paper explains what you can do to help protect your organization, and it discusses an approach for improving your organization’s Web application security.
    FREE! Go There Now!


    NEW! Webcast: Eclipse: Empowering the universal platform

    The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now.
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    SEARCH CODE ARTICLES

    - PHP IP Blocking
    - Search engine with ranking feature
    - Ajax access to Google API
    - Table Searcher
    - Search_It
    - FTP SEARCH
    - Search and Replace class
    - Simple Search on mysql database
    - Search Your Database
    - search_v1.1
    - Database Searching Class






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway