0

I have a script that creates files with some data in it. The contents are seperated by div with classes such as :

<div class="2017-02-01-20-35-company1">
//content
</div>
<div class="2017-02-01-20-35-company2">
//content
</div>

However, I want to be able to edit/delete each div from the created file, not just create the file or delete it entirely. I can retrieve the name of the file and the name of div.

But is it possible to delete the div I want to delete as well as its content ?

thanks.

anju
  • 589
  • 12
  • 25
Nolan.K
  • 185
  • 2
  • 18
  • 2
    Keep the information you use to generate the file in a different format, either in the database or in a file, operate the changes on it and regenerate the HTML file after each change. It's easier and less error prone. – axiac Jun 28 '17 at 08:26
  • Read this maybe: https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php – timiTao Jun 28 '17 at 08:27
  • 2
    You certainly can use a DOM parser to work on such structure. But keeping it in a file means you have to re-read, re-parse and re-write it for every modification. It makes much more sense to keep the information in some storage location that is much better suited for such tasks, typically a database as @axiac mentions above, and only export the current state the moment you actually need it. – arkascha Jun 28 '17 at 08:30

1 Answers1

1

Assuming you know the class of the div you want to remove it using a regex pattern to capture everything between the known div including its tag.

This is achieved through the use of preg_replace()

The method i would follow is:

<?php
//Set div class string to remove
$classString = "2017-02-01-20-35-company1";

//Get file contents
$contents = file_get_contents("/path/to/file.html");

//Remove div from contents
$search = '/[<div class="'.$classString.'">](.*)[<\/div>]/';
$contents = preg_replace($search, '', $contents);

//Save file again
file_put_contents("/path/to/file.html", $contents);
JParkinson1991
  • 1,256
  • 1
  • 7
  • 17