当类匹配某些模式时,如何从整个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。
答案 0 :(得分: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));
答案 1 :(得分: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)
?>