Replace between two lines - HELP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jpell7
Forum Newbie
Posts: 6
Joined: Fri Jan 02, 2004 4:28 pm

Replace between two lines - HELP

Post 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]
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

You need at least to include m modificator to that pattern. (or it won't work with multiline $data)
jpell7
Forum Newbie
Posts: 6
Joined: Fri Jan 02, 2004 4:28 pm

Post by jpell7 »

where would I put that m modifier? I am really bad at making preg_ patterns :cry:
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post 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);

?>
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

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

the letters in bold are modifiers
Post Reply