I have a sting which happens to be HTML, and I wish to delete specific sections of it serverside using PHP (no JavaScript/jQuery solutions please). The string will need to have certain identifiers in it to tag sections which might wish to be removed, and I will also have some variable which indicates which tagged sections should be removed. These indicator tags should not remain in the final modified string.
For instance, consider $html_1
where I included a capture
attribute to tag the sections which might be deleted. Or $html_2
where I wrapped [capture]
around the tags which might be deleted. Note that these were just two possible ways I thought of tagging the sections, and am okay with any other method which allows the string to be stored in a DB.
For both, I have a <h2>
block, <h1>
block, and <p>
block where capture
is used to indicate sections which may or may not be removed. Then given $modify
which indicates which sections should or shouldn't be removed, how can I generate the new string which is equal to $html_new
? I am thinking maybe a DOMDocument
, str_replace
, or regex solution might work, but not sure.
<?php
$html_1 = <<<EOT
<div>
<div>
<div>
<h1 capture="a">bla bla bla</h1>
<p>bla</p>
<h2 capture="b">bla bla<span>bla</span></h2>
<h1>bla bla bla bla</h1>
</div>
</div>
<div>
<p capture="c">bla bla bla</p>
<h1>bla bla</h1>
</div>
</div>
EOT;
$html_2 = <<<EOT
<div>
<div>
<div>
[caption id="a"]<h1>bla bla bla</h1>[/caption]
<p>bla</p>
[caption id="b"]<h2>bla bla<span>bla</span></h2>[/caption]
<h1>bla bla bla bla</h1>
</div>
</div>
<div>
[caption id="c"]<p>bla bla bla</p>[/caption]
<h1>bla bla</h1>
</div>
</div>
EOT;
$modify=array('a'=>true,'b'=>false,'c'=>true);
$html_new = <<<EOT
<div>
<div>
<div>
<p>bla</p>
<h2>bla bla</h2>
<h1>bla bla bla bla</h1>
</div>
</div>
<div>
<h1>bla bla</h1>
</div>
</div>
EOT;
?>