Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

in PHP, how to remove specific class from html tag?

given the following string 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 empty or remove any class that has "test2" in it, so the result would be this:

<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>

of if you're removing the element:

<div>
<p>text 1</p>
<p>text 2</p>
<p><span class='test1'>text 3</span></p>
<p>text 4</p>
</div>

I'm happy to use a regex expression or something like PHP Simple HTML DOM Parser, but I have no clue how to use it. And with regex, I know how to find the element, but not the specific attribute associated w/ it, especially if there are multiple attributes like my example above. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The DOMDocument class is a very straight-forward and easy-to-understand interface designed to assist you in working with your data in a DOM-like fashion. Querying your DOM with xpath selectors should be the task(s) all the more trivial:

Clear All Classes

// 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...