Re: Edit a file

From: Date: Sun, 18 May 2003 17:48:13 +0000
Subject: Re: Edit a file
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-148102@lists.php.net to get a copy of this message
On Sun, 18 May 2003 16:18:00 +0100, you wrote: >Thanks for your reply, but this question is different! > >what i am trying to do is create a script that replaces a certain part of a >page e.g. everything between the <script> </script> tags. > >The problem i found with the fopen() function is that writing to a file >automatically wipes the original content from the file... Ok, then you need to do a sequence of things: 1. Read the contents of the old file into memory 2. Replace everything between <script> and </script> 3. Write out the changed text to the new file (may be the same file) In an older language there might be more steps, but PHP has a few neat functions that simplify things (the code below uses file_get_contents(), available in PHP 4.3 and above. Replace with file() if you prefer) However, this is a more difficult task it first appears. Some problems you ought to consider: What is the <script> tag has attribues? eg <script lang="Javascript"> What if the file is insanely large? What if the file has more than one <script/> block? What if the read or write fails? What about <SCRIPT> and <ScRiPt>? The following function is a quick hack rather than a solution, but it should get you started: /* this function replaces any <script></script> block in $oldFilename with $newText, and writes the result to $newFilename. Matching is greedy */ function replaceScriptBlock ($oldFilename, $newFilename, $newText) { /* read the contents of $oldFilename into memory */ $text = file_get_contents ($oldFilename); /* replace everything between <script> and </script> with $newText */ $text = ereg_replace("<script>.*</script>", $newText, $text); /* write out the changed text to $newFilename */ //file_put_contents ($newFilename, $text); $f = fopen($newFilename, 'w'); fwrite($f, $text, strlen($text)); fclose($f); }

« previous php.general (#148102) next »