...

View Full Version : Replace data in a file



DesignersToolz
04-01-2004, 03:08 AM
I know I posted about this before but it was awhile ago and the thread just confused everyone. Problem never got solved, gave up on it awhile so now I'll get back to it. :cool:




What I'm trying to do is replace data in a file. Example:


file foo.txt contains:


<!-- 9 --> random text. <!-- /9 -->
<!-- 14 --> some more random text. <!-- /14 -->


Now, what I want to do is replace whats between a delimiter set. Lets say 14. So I'd want to delete it. Delimiters and all, so all thats left is:

<!-- 9 --> random text. <!-- /9 -->


So how would I go about this?


Thanks :D

dswimboy
04-01-2004, 03:20 AM
$file = file_get_contents('foo.txt');
$rem = "4"; // remove delimeter with this num
preg_replace("/<!-- $rem -->.*?<!-- \/$rem -->/", "", $file);


i haven't tested this, just threw it together. the question mark makes the match not-greedy. i know it works in perl, and i'm hoping the preg functions match perl's RegEx syntax exactly.

DesignersToolz
04-01-2004, 02:26 PM
I can work with that :) Thanks for the help bro :thumbsup:

DesignersToolz
04-01-2004, 02:55 PM
Slight problem.


I need it to work on multiple lines.

Example:

Like it is now it will only work if its set up like this:
<!-- 14 --> some more random text. <!-- /14 -->


I need it to work with multiple lines like so:

<!-- 14 -->

some
more
random

text.

<!-- /14 -->

Hawkmoon
04-01-2004, 05:59 PM
Here is some code that would work...a bit wordy...but it does the trick.

-Hawk



<?
$strFile = file_get_contents($fileName);

$id = "14"; //or whatever;
$openTag = "<!-- $id -->";
$closeTag = "<!-- /$id -->";
$startExtract = strpos($strFile,$openTag);
$endExtract = strpos($strFile,$closeTag)+strlen($endExtract);

$strTop = substr($strFile,0,$startExtract);
$strBottom = substr($strFile,$endExtract,strlen($strFile));

$strOutput = $strTop . $strBottom;
?>

dswimboy
04-01-2004, 06:32 PM
try either:

preg_replace("/<!-- $rem -->.*?<!-- \/$rem -->/m", "", $file);
// OR
preg_replace("/<!-- $rem -->.*?<!-- \/$rem -->/s", "", $file);


i think one of them will allow you to match a string with newlines. when i get home, i'll check my book and let you know. this allows it to be a little less wordy for you :)

DesignersToolz
04-01-2004, 06:46 PM
preg_replace("/<!-- $rem -->.*?<!-- \/$rem -->/s", "", $file);



Did the trick. Thanks :thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum