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

后端 未结 4 886
忘了有多久
忘了有多久 2020-12-15 14:24

given the following string in PHP:

$html = \"

text 1

相关标签:
4条回答
  • 2020-12-15 14:58

    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);
    
    0 讨论(0)
  • 2020-12-15 15:02

    using the PHP Simple HTML DOM Parser

    Updated and tested! You can get the simple_html_dom.php include from the above link or here.

    for both cases:

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

    case 1:

    foreach($html->find('span[class*="test2"]') as $e)
    $e->class = '';
    
    echo $html;
    

    case 2:

    foreach($html->find('span[class*="test2"]') as $e)
    $e->parent()->innertext = $e->plaintext;
    
    echo $html;
    
    0 讨论(0)
  • 2020-12-15 15:16

    You can use any DOM Parser, iterate over every element. Check whether its class attribute contains test2 class (strpos()) if so then set empty string as a value for class attribute.

    You can also use regular expressions to do that - much shorter way. Just find and replace (preg_replace()) using the following expression: #class=".*?test2.*?"#is

    0 讨论(0)
  • 2020-12-15 15:20
    $notest2 = preg_replace(
             "/class\s*=\s*'[^\']*test2[^\']*'/", 
             "class=''", 
             $src);
    

    C.

    0 讨论(0)
提交回复
热议问题