Search code examples
phpfilefopenfwrite

PHP : How to Replace some text from n th line to m th line from file?


I have a file like some.txt having content :

#start-first
Line 1
Line 2
Line 3
#end-first

#start-second
Line 1
Line 2
Line 3
Line 4
#end-second

#start-n
Line 1
Line 2
Line 3
Line 4
...
...
#end-n

I want to delete content from file from #start-second to #end-second or from #start-n to #end-n, actually #start-second is Start Marker for Second Text Block of file and #end-second is End Marker for Second Text Block of file.

How to delete content from Specific Start Block to same End block ?


Solution

  • If these files are really big, there is a fairly lightweight solution:

    $file = file_get_contents("example.txt");
    // Find the start "#start-$block", "#end-$block" and the length between them:
    $start = strpos($file, "#start-$block");
    $end = strpos($file, "#end-$block");
    $length = $end-$start+strlen("#end-$block");
    
    $file = substr_replace($file, '', $start, length);
    file_put_contents("example.txt", $file);
    

    My original answer started with a regex:

    $block = 4;
    
    // Open the file
    $file = openfile("example.txt");
    
    // replace #start-$block, #end-$block, and everything inbetween with ''
    $file = preg_replace("/#start\-".$block."(?:.*?)#end\-".$block."/s", '', $file);
    
    // Save the changes
    file_put_contents("example.txt", $file);
    

    Regexes are expensive though, but sometimes easier to understand.