PHP相当于jQuery的addClass函数

7
您如何使用PHP将名称为newClass的类添加到像<a class='abc'><p style=display:block>这样的开始标签中?

1
在使用 PHP 解析现有文件或使用 PHP 生成文件时? - deceze
它是由系统自动生成的,只有一个起始标签。 - jantimon
那么,您并没有解析现有的文件?那么通常的方法就是在应该出现的位置写入 class="newClass" ... 您能否澄清您的情况? - deceze
我的函数生成两个HTML代码之间的差异。修改后的字符串被包装在一个新的span中,但是修改现有元素应该获得一个额外的类。 - jantimon
@Ghommey 我非常推荐使用DOM*功能来完成这个任务。如果您能提供更详细的示例,我们一定可以更好地帮助您。 - Yoshi
我的函数的原因类似于这个线程:https://dev59.com/B3VD5IYBdhLWcg3wRpiX - jantimon
2个回答

9

正则表达式示例:

<?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/zh/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必须是格式良好的。


闭合标签是否必需,或者这个也可以工作吗 echo addClass('<a class="abc">', 'newClass'); ? - jantimon
它正在尝试解析XML,所以我希望不会 :-) 肯定jQuery也不允许你这样做吧? - Rudi Visser
我想我必须使用正则表达式。 - jantimon
@Ghommey,我不建议这样做,因为你之前的评论表明,你正在进行大量的DOM操作。也许你最好还是使用DOM来完成这个任务? - Yoshi
我正在使用一个返回字符串数组的差异算法,我无法更改它。 - jantimon
显示剩余3条评论

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接