PHP equivalent to jQuery addClass

落爺英雄遲暮 提交于 2020-01-03 08:53:14

问题


How would you add a class named newClass to an opening tag like <a class='abc'> or <p style=display:block> using php?


回答1:


Regexp example:

<?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');

using http://php.net/manual/en/book.dom.php example

<?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);
}

I'm purposely not using loadHTML (inside the function) to prevent having to dive down into the autogenerated html structure to find the actual given $htmlString. This of course implies that $htmlString has to be well-formed.




回答2:


Html class from Nette Framework does a perfect work for generating HTML tags in PHP.



来源:https://stackoverflow.com/questions/6056130/php-equivalent-to-jquery-addclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!