gpt4 book ai didi

PHP 相当于 jQuery addClass

转载 作者:可可西里 更新时间:2023-11-01 12:50:09 28 4
gpt4 key购买 nike

您将如何添加一个名为 newClass 的类?到一个 opening 标签,例如 <a class='abc'><p style=display:block>使用 PHP?

最佳答案

正则表达式示例:

<?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 必须格式正确。

关于PHP 相当于 jQuery addClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6056130/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com