In PHP, how to remove a specific class from an html tag?
The following line is given in PHP:
$html = "<div>
<p><span class='test1 test2 test3'>text 1</span></p>
<p><span class='test1 test2'>text 2</span></p>
<p><span class='test1'>text 3</span></p>
<p><span class='test1 test3 test2'>text 4</span></p>
</div>";
I just want to either delete or delete any class with "test2", so the result will be as follows:
<div>
<p><span class=''>text 1</span></p>
<p><span class=''>text 2</span></p>
<p><span class='test1'>text 3</span></p>
<p><span class=''>text 4</span></p>
</div>
if you delete the item:
<div>
<p>text 1</p>
<p>text 2</p>
<p><span class='test1'>text 3</span></p>
<p>text 4</p>
</div>
I'm glad to use a regex expression or something like PHP Simple HTML DOM Parser, but I don't know how to use it. And with a regex, I know how to find an element, but not the specific attribute associated with it, especially if there are several attributes like my example above. Any ideas?
using PHP Simple HTML DOM Parser
:
include('../simple_html_dom.php');
$html = str_get_html("<div><p><span class='test1 test2 test3'>text 1</span></p>
<p><span class='test1 test2'>text 2</span></p>
<p><span class='test1'>text 3</span></p>
<p><span class='test1 test3 test2'>text 4</span></p></div>");
1:
foreach($html->find('span[class*="test2"]') as $e)
$e->class = '';
echo $html;
2:
foreach($html->find('span[class*="test2"]') as $e)
$e->parent()->innertext = $e->plaintext;
echo $html;
DOMDocument - , DOM- . DOM xpath (-) :
// Build our DOMDocument, and load our HTML
$doc = new DOMDocument();
$doc->loadHTML($html);
// Preserve a reference to our DIV container
$div = $doc->getElementsByTagName("div")->item(0);
// New-up an instance of our DOMXPath class
$xpath = new DOMXPath($doc);
// Find all elements whose class attribute has test2
$elements = $xpath->query("//*[contains(@class,'test2')]");
// Cycle over each, remove attribute 'class'
foreach ($elements as $element) {
// Empty out the class attribute value
$element->attributes->getNamedItem("class")->nodeValue = '';
// Or remove the attribute entirely
// $element->removeAttribute("class");
}
// Output the HTML of our container
echo $doc->saveHTML($div);
DOM Parser, . , class test2 class (strpos()), class .
You can also use regular expressions for this - a much shorter way. Just find and replace ( preg_replace () ) using the following expression:#class=".*?test2.*?"#is