Page 1 of 1

Replace between two lines - HELP

Posted: Fri Jan 02, 2004 4:28 pm
by jpell7
Hi, I would like to replace everything between the lines:
// Start here

and

// End here

in this file:

//Start Here

Hello
Goodbye
Testing
Today I went to the mall

//End Here


So basically, I would like to have the script find the line "// Start Here" and begin replaceing everything (and including the line //Start Here) with blankspace until it reaches //End Here


Heres what I have for code now, and I know my preg_replace function is most likely not working:

Code: Select all

<?

$handle=fopen("test.php", "r+");
$data=fread($handle,filesize("test.php"));

preg_replace( '#// Start Here.*?// End Here#gis', '', $data);

fwrite($handle,$data);

fclose($handle);

?>
[/quote]

Posted: Fri Jan 02, 2004 5:15 pm
by Weirdan
You need at least to include m modificator to that pattern. (or it won't work with multiline $data)

Posted: Fri Jan 02, 2004 5:26 pm
by jpell7
where would I put that m modifier? I am really bad at making preg_ patterns :cry:

Posted: Fri Jan 02, 2004 5:40 pm
by redmonkey
You will need to open the file twice, once to read it's contents and a second time to truncate it's length to zero and write the new contents.

If you just open it for reading and writing you are just over-writing the contents so if the replacement contents is shorter in length than the original then some of the original contents will still be contained in the file.

Try the code below, complete with PCRE match pattern, untested but should work.

Code: Select all

<?php

$reading=fopen("test.php", "r");
$data=fread($reading,filesize("test.php"));
fclose($reading);

$newdata = preg_replace( '/\/\/\s?Start here.*\/\/\s?End here/s', '', $data);
$writing=fopen("test.php", "w");
fwrite($writing,$newdata);
fclose($writing);

?>

Posted: Sat Jan 03, 2004 1:07 pm
by Weirdan
preg_replace( '#// Start Here.*?// End Here#gis', '', $data);

the letters in bold are modifiers