views:

67

answers:

2

After using file_get_contents to write to a html file, I need to delete certain parts of this files contents because the paths to css and images has changed.

So I have lines as below :

 <link href="/Elements/css/main.css" rel="stylesheet" type="text/css">
  <image src="/Elements/images/image1.gif" />

I would like to remove the: '/Elements/' part of these two lines, and others so I will have the correct paths.

thanks

R

+3  A: 

And what exactly is your problem? Just use str_replace or preg_replace (use the latter only if you need regular expressions, ie. if it's not a simple search & replace) on the string you got from file_get_contents, and save it back to disk.

ie.

$text = file_get_contents("yourfile.html");
$text = str_replace("/Elements/", "", $text);
file_put_contents("yourfile.html", $text);
wimvds
If the file contains more than the just the shown pathes, it makes sense to actually replace the pathes one by one, e.g. `str_replace("/Elements/css/main.css", "/css/main.css", $html);` to prevent accidental removal in other pathes. Or pass in arrays.
Gordon
wimvds
Yes, I wanted to suggest DOM Parser myself, but the UseCase seems too simple for really needing that.
Gordon
Instead of re-opening and saving back to disk, is it possible to delete from the original when using file_get_contents
Rifki
And how do you expect these changes to be kept without saving them? So, no, you can't remove them and keep the changes without saving the changes back to disk.
wimvds
+2  A: 

Hi there, i did this once for editing BIND zone files. The best solution is reading the file into a big array, find the lines you want to delete. Unset or edit those lines and push the array back into a file.

This is how you read a file into an array:

$html = file("something.html");

Find the line you want like so:

foreach($html as $key => $line)
{
  $html[$key] = str_replace("/Elements/", "", $line); 
}

then write it all back to a file

$fp=fopen("something.html","w+");
foreach($html as $key => $value)
{
   fwrite($fp,$value."\t");
}

if you know regular expressions, you could also look into that (that's what i used). Then use preg_replace.

Good luck

Stephen
Why would you even bother reading them into an array when you can just read the file in one go, replace the relevant parts and save the modified file.
wimvds
Because this proven to be a way safer way because you can check each line instead of treating the entire file with an action. This has proven to be problematic in-practice.
Stephen