Write to file from certain point

I need some help coding a php script, to open a file in write mode
then, search for a start point to an end where to write, and put the content in this area, and save the whole file with new content
for example:

azertiyo
...
...
##Start
hello
something
123456
654321
##End
...
...
pouzyer

What have you tried?

1 Like

i got this so far :

    function editfile( $sourcefile, $start='##start', $end='##end', $data=array() ){
    /*
        create a filtered array of lines
    */
    $lines=array_filter( file( $sourcefile , FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES ) );

    /* begin generating output */
    $output=array_merge(
        /* add content that appears before the `start` marker and including the marker */
        array_splice( $lines, 0, array_search( strtolower( $start ), array_map('strtolower', $lines ) ) + 1 ),

        /* add the new data, whatever that is to be */
        $data,

        /* add the content that appeared after the `end` marker - including the marker */
        array_splice( $lines, array_search( strtolower( $end ), array_map('strtolower', $lines ) ) )
    );

    /* write the new array back to the same file as individual lines */
    file_put_contents( $sourcefile, implode( PHP_EOL, $output ) );
}

editfile( 'test.txt', '##Start', '##end', array('1','..','2','..','3','..','4','..','5') );

the only problem that i can’t do it, is :

in case i receive the content from reading another file, how can i declare everyline received from file’s content to that array to be sent to the function ?

Sponsor our Newsletter | Privacy Policy | Terms of Service