SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    Feel my RewiredMind KMxRetro's Avatar
    Join Date
    Jan 2001
    Location
    Exeter, Devon, UK
    Posts
    477
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Search/Replace in a file

    Hi folks,
    Can anyone help with this?

    I have a file which has two comment markers, both called <!--TABREPLACE-->. What I want to do, is open the file (from another scripts) and overwrite all content between the two instances of <!--TABREPLACE-->. Is there a simple way of doing this? Also, the two <!--TABREPLACE--> comments need to be left untouched for the next running of the scripts.

    Any ideas?

    Thanks,

  2. #2
    What's HTML?
    Join Date
    May 2001
    Location
    San Diego, CA
    Posts
    1,701
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think that would involve regular expressions, which I know very little about. I'll leave the answer up to the PHP guru's.
    Ryan Kuhle - A Proud Advisor - Got Questions? Just Ask!
    Get your website started for less than $20! Click Here

  3. #3
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I know what you are thinking RKuhle, hmm looks complicated, must involve regex But that's the beauty of PHP, there are fantastic functions built in that do amazing things with strings and arrays.
    PHP Code:
    <?php

    $filename 
    './foo.txt';

    // note: for safety reasons
    // you should back up the file before
    // you do anything
    // but you can code that

    // open the file and read the file into a string buffer
    $fp fopen($filename"r");

     while (!
    feof($fp)) {
       
    $buffer .= fgets($fp,4096);
    }
    // close the file
    fclose($fp);

    $delimiter '<!--TABREPLACE-->';

    // extract the tokens out of the buffer
    // into an array, using the delimiter
    $tokens explode($delimiter$buffer);

    // perform the substitution on the string in $tokens[1]
    $substituteString 'foo bar zoot bah humbug';
    $tokens[1] = $substituteString;

    // implode the array $tokens back into a string
    $buffer implode($delimiter$tokens);

    // write $buffer out to file
    $fp fopen($filename"w");
    fwrite($fp$buffer);
    fclose($fp);

    // better keep the client browser happy ;-)
    echo 'done';
    ?>
    I could have opened the file only once using the "r+" mode and mucked about with resetting the internal pointer when we were ready to write out - but that's too complicated for a simple person like me


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •