tags:

views:

100

answers:

4

Hi

I have this string:

$str = '<div class="defaultClass">...</div>';

how do I append 'myClass' next to 'defaultClass' ?

+3  A: 

The "class" attribute is just a space separated list of classes.

$str = '<div class="defaultClass myClass">...</div>';

Or you could hack it together like this:

$str = '<div class="defaultClass">...</div>';
$str = str_replace('class="defaultClass', 'class="myClass defaultClass', $str);
//Result: <div class="myClass defaultClass">...</div>

Or with regular expressions:

$str = '<div class="defaultClass">...</div>';
$str = preg_replace(':class="(.*defaultClass.*)":', 'class="\1 myClass"', $str);
//Result: <div class="defaultClass myClass">...</div>

Other solutions include using XML to add it to the DOM node, which is probably less error prone but more advanced and resource heavy.

Emil Vikström
I'd hazard a guess that he's asking how to do it programmatically :-)
Andy E
thanks, I used str_replace to do this :P
Alex
A: 
$str = '<div class="defaultClass ' . $myclass . '">...</div>';

This assumes myClass is variable

DRL
A: 

I would take a look at a system Called SimpleDom!

Heres a small example!

// Create DOM from string
$html = str_get_html('<div class="defaultClass"><strong>Robert Pitt</strong></div>');

$html->find('div', 1)->class = 'SomeClass';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

Some more examples: http://simplehtmldom.sourceforge.net/manual.htm

Some Downloads ;): http://simplehtmldom.sourceforge.net/

RobertPitt
A: 

With native DOM:

$dom = new DOMDocument;
$dom->loadHTML('<div class="defaultClass">...</div>');
$divs = $dom->getElementsByTagName('div');
foreach($divs as $div) {
    $div->setAttribute('class', 
        $div->getAttribute('class') . ' some-other-class');
}

echo $dom->saveHTML();
Gordon