Page 1 of 1

File editing question - Update file between 2 points?

Posted: Mon Jan 03, 2005 1:12 pm
by idotcom
Hi

I am wanting to use php to open a file and update data between two points.

Example:

this is other file content ----------------------------------------
this is other file content ----------------------------------------
this is other file content ----------------------------------------
this is other file content ----------------------------------------
this is other file content ----------------------------------------
this is other file content ----------------------------------------
<!-- UPDATE AREA START -->

updatable content here

<!-- UPDATE AREA END -->




Is this doable without exploding the whole files content into an array, storing, finding the update area, modify, then writing back...?

Can I just update between the comments???

Any help would be greatly appreciated.

Thanks

Posted: Mon Jan 03, 2005 1:20 pm
by feyd
regular expression functions work well in this area: [php_man]preg_replace()[/php_man]

Devnetwork search: [devnet]preg_replace[/devnet]

Posted: Mon Jan 03, 2005 5:57 pm
by ianlandsman
Yeah it's a pain but there isn't a super easy way. You have to read the entire file in. At that point you could use it as a giant string and use regex as feyd says or put it into an array, etc but either way you need to bring it all in and work with it. Best bet is to build a nice little function/class to handle it so at least when you call the code it doesn't infuriate you! Turning a bunch of lines of code into a UpdateFileComments() function makes it all better, at least mentally.

Posted: Mon Jan 03, 2005 6:00 pm
by idotcom
Could anyone tell me why this is not working???

I have a file with content like the example above.

----------------- all kinds of content -----------------
----------------- all kinds of content -----------------
----------------- all kinds of content -----------------
----------------- all kinds of content -----------------
<!--START-->

replace anything within these comment tags

<!--END-->


Code: Select all

<?php

$thefilecontent = implode("",file("$pathtofile"));

$replaced = preg_replace('/(<!--START-->)(.*)(<!--END-->)/', "$withthis", $thefilecontent);

?>
Feyd... any thoughts?

Thanks again :roll:

Posted: Mon Jan 03, 2005 7:39 pm
by w.geoghegan
Hi,

If it's a PHP file you're wanting to update I would suggest storing the data in a text file and then using this in the PHP file.

Code: Select all

<START>

<?
include("filedata.txt");
?>

</END>

Posted: Mon Jan 03, 2005 7:45 pm
by redmonkey
Try using...

Code: Select all

$replaced = preg_replace('/(<!--START-->)(.*)(<!--END-->)/s', "$withthis", $thefilecontent);