Replace a string in a file?

Discussion in 'PHP' started by bobby9101, May 30, 2007.

  1. #1
    Hi, I have a file (test.txt) that looks like:

    wfawfawaf
    [COLOR=Red]Unique Text
    bogfwg
    wfawgw
    gwa
    wa
    gagwgawwga
    ggawgwa
    
    wag
    gwawgwagwagwag
    gagwgwa
    End Unique Text[/COLOR]
    
    wfanwfa
    gawfwfafwa
    gaefwawfa
    Code (markup):
    I would to replace the red text with $testvar

    How do I do that?

    I could just read out the file using file_get_contents()
    then change the content with str_replace()
    then put it back with file_put_contents()
    Is that the best way?

    problem is, the file can get big, and it sounds like overkill
     
    bobby9101, May 30, 2007 IP
  2. gibex

    gibex Active Member

    Messages:
    1,060
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    95
    #2
    how big is your file and you have php5 (to use file_put_contents) ?
     
    gibex, May 30, 2007 IP
  3. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #3
    well the size can change.
    But i have decided to just use the method I described in the first post.
     
    bobby9101, May 30, 2007 IP
  4. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #4
    Read in blocks, especially if the text you are replacing only occurs once.

    You can then optimise by starting off at a certain point if you know roughly where the unique text is located etc.
     
    krt, May 30, 2007 IP