PHP相当于jQuery addClass
发布时间:2020-12-13 18:15:42 所属栏目:PHP教程 来源:网络整理
导读:如何将一个名为newClass的类添加到开头标记中,例如 a class ='abc'或 p style = display:block使用 PHP? Regexp示例: ?phpfunction addClass($htmlString = '',$newClass) { $pattern = '/class="([^"]*)"/'; // class attribute set if (preg_match($pat
如何将一个名为newClass的类添加到开头标记中,例如< a class ='abc'>或< p style = display:block>使用
PHP?
Regexp示例:
<?php function addClass($htmlString = '',$newClass) { $pattern = '/class="([^"]*)"/'; // class attribute set if (preg_match($pattern,$htmlString,$matches)) { $definedClasses = explode(' ',$matches[1]); if (!in_array($newClass,$definedClasses)) { $definedClasses[] = $newClass; $htmlString = str_replace($matches[0],sprintf('class="%s"',implode(' ',$definedClasses)),$htmlString); } } // class attribute not set else { $htmlString = preg_replace('/(&;.+s)/',sprintf('$1class="%s" ',$newClass),$htmlString); } return $htmlString; } echo addClass('<a class="abc">','newClass'); echo addClass('<p style=display:block>','newClass'); 使用http://php.net/manual/en/book.dom.php示例 <?php function addClass($node = null,$className) { $result = false; if (is_string($node)) { $dom = DOMDocument::loadXml($node); if ($dom instanceof DOMDocument) { $definedClasses = explode(' ',$dom->documentElement->getAttribute('class')); if (!in_array($className,$definedClasses)) { $dom->documentElement->setAttribute( 'class',$dom->documentElement->getAttribute('class') . ' ' . $className ); } $result = $dom->saveXml($dom->documentElement,true); } } elseif ($node instanceof DOMElement) { // this code repetition,could of course be avoided using some more sophisticated structures $definedClasses = explode(' ',$node->getAttribute('class')); if (!in_array($className,$definedClasses)) { $node->setAttribute('class',$node->getAttribute('class') . ' ' . $className); } $result = $node; } return $result; } // using a string as input echo addClass('<a class="abc"></a>','newClass'); // using a DOMElement as input $dom = DOMDocument::loadHtml('<div><a id="something"></a></div>'); $xpath = new DOMXPath($dom); $node = $xpath->query('//*[@id="something"]')->item(0); if ($node instanceof DOMElement) { addClass($node,'newClass'); echo $dom->saveXml($node,true); } 我故意不使用loadHTML(在函数内部)来防止不得不深入到自动生成的html结构中来找到实际给定的$htmlString.这当然意味着$htmlString必须格式正确. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |