I have a variable in which I store some HTML code. Let's say:
<div>
<span> test of {my_string} </span>
{my_string}
test of {my_string}
</div>
<h1> {my_string} </h1>
I would need to remove some lines containing a specific value so the end result looks like:
<div>
</div>
So I was thinking of getting the position of the string with strpos
and then get the which are before and after. But how can I search backwards with
strpos
as I already have an offset specified?
$rep_pos = strpos($message, 'my_string');
$line_begining = ????
$line_end = strpos($message, '
', $rep_pos);
I can't use strip_tags
because I don't know in advance what will be the tags around and some other strings can use the same tags.
You should use DOMDocument
for parsing HTML tags string. Here we are using XPath query
which is //*[text()=" my_string "]
which means get all elements which contains my_string
text.
<?php
ini_set('display_errors', 1);
$string='<html>
<body>
<div>
<span> my_string </span>
</div>
<h1> my_string </h1>
</body>
</html>';
$domobject= new DOMDocument();
$domobject->loadHTML($string);
$xpath= new DOMXPath($domobject);
$result=$xpath->query('//*[text()=" my_string "]');
Foreach($result as $nodes)
{
$nodes->parentNode->removeChild($nodes);
}
echo $domobject->saveHTML();
Solution 2: