Hi
I have this string:
$str = '<div class="defaultClass">...</div>';
how do I append 'myClass' next to 'defaultClass' ?
Hi
I have this string:
$str = '<div class="defaultClass">...</div>';
how do I append 'myClass' next to 'defaultClass' ?
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.
$str = '<div class="defaultClass ' . $myclass . '">...</div>';
This assumes myClass is variable
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/