脚本宝典收集整理的这篇文章主要介绍了PHP相当于jQuery addClass,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
<?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->@R_512_116@( '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必须格式正确.
以上是脚本宝典为你收集整理的PHP相当于jQuery addClass全部内容,希望文章能够帮你解决PHP相当于jQuery addClass所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。