PHP:从引号之间删除重复的单词

Bri*_*ham 1 php regex preg-replace

如何从以下字符串中的class =""之间删除重复项?

<li class="active active"><a href="http://netcoding.net/indev/sample-page/">Sample Page</a></li>
Run Code Online (Sandbox Code Playgroud)

请注意,所显示的课程可能会发生变化并处于不同的位置.

anu*_*ava 7

您可以使用DOM解析器然后explodearray_unique:

$html = '<li class="active active">
         <a href="http://netcoding.net/indev/sample-page/">Sample Page</a></li>';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//li");
for($i=0; $i < $nodelist->length; $i++) {
    $node = $nodelist->item($i);
    $tok = explode(' ', $node->getAttribute('class'));
    $tok = array_unique($tok);
    $node->setAttribute('class', implode(' ', $tok));
}
$html = $doc->saveHTML();
echo $html;
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

<html><body>
<li class="active"><a href="http://netcoding.net/indev/sample-page/">Sample Page</a></li>
</body></html>
Run Code Online (Sandbox Code Playgroud)

在线演示

  • 大声笑:)我不是专业的PHP程序员,但我过去使用DOM回答了很多. (2认同)
  • @BrianGraham,Nope在这里看到演示https://eval.in/130904代码非常完美. (2认同)