2

How to remove all classes from entire html string (a lot of elements) when class match some pattern (let's say begins with something-)

So

input

<div class="something-first">
    <div class="something-child something-good another something-great">
    </div>
</div>

would become

<div class="">
    <div class="another">
    </div>
</div>

I need to do it server-side so it needs php.

Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91
  • 2
    If this HTML generated by the PHP? Is so, how? (Show code.) If not, where does it come from? – user2864740 Nov 08 '13 at 07:15
  • I get the content by wordpress get_the_content(); function. I need to hide some informations for not authorized users, but I can't remove it. – Adam Pietrasiak Nov 08 '13 at 07:24
  • While a regex "would work" (most of the time), it's just asking for pain. Hopefully someone will suggest a good method of HTML manipulation. – user2864740 Nov 08 '13 at 07:28
  • 1
    See http://stackoverflow.com/a/13548139/2864740 , http://stackoverflow.com/a/2108735/2864740 , http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php/3577662#3577662 YMMV – user2864740 Nov 08 '13 at 07:29

2 Answers2

2

Use DOM manipulation:

$html = '<div class="something-first">
    <div class="something-child something-good another something-great">
    </div>
</div>';

$domDoc = new DOMDocument();
$domDoc->loadHTML($html);
$xpath = new DOMXPath($domDoc);

$nodes = $xpath->query('//*[starts-with(@class, "something-")]');

foreach($nodes as $n) {
    $classes = preg_split('/\s+/',$n->getAttribute('class'));

    $newClasses = array();

    foreach($classes as $class) {
        if(strpos($class, 'something-') === 0)
            continue;

        $newClasses[] = $class;
    }

    $n->setAttribute('class', implode(' ', $newClasses));
}


$newHtml = '';

foreach($xpath->query('//body/*') as $node) {
    $newHtml .= $domDoc->saveHTML($node);
}

var_dump(htmlentities($newHtml));
TiMESPLiNTER
  • 5,741
  • 2
  • 28
  • 64
0
<?php
$file = fopen("<filename>", "w+");
$words = array();
$new = array();
$filecontents = file_get_contents('<filename>');
$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);
$i=0;
  foreach($words as $word) {
     if(substr($word[0],0,11) == '"something-" or substr($word[0],0,10) == 'something-") {
     $new[] = "";
     } else {
       $new[] = $word;
       }
   $i++; 
   }
fwrite($file,$new)
?>
uvais
  • 416
  • 2
  • 6