2

当类匹配某些模式时如何从整个 html 字符串(很多元素)中删除所有类(假设以 开头something-

所以

输入

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

会成为

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

我需要在服务器端做,所以它需要 php。

4

2 回答 2

2

使用 DOM 操作:

$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));
于 2013-11-08T07:23:15.193 回答
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)
?>
于 2013-11-08T08:21:39.903 回答