6

I have this string:

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

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

1
  • 1
    Is the ellipsis (...) actually those three periods or could it be any series of characters? What else in the string may be different to your example? Really, the simple answer to your question is just to type 'myClass' next to defaultClass, but I'm assuming you'll need to perform this operation on multiple different (and unpredictable) strings. :P Commented Jun 28, 2010 at 11:02

4 Answers 4

9

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();
Sign up to request clarification or add additional context in comments.

Comments

7

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.

1 Comment

I'd hazard a guess that he's asking how to do it programmatically :-)
1

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/

1 Comment

I've used this library for quite a while but I had to switch because it just became so slow. The built in PHP one is crazy fast, only down side is that you can only access things via xpath (but there are libraries to convert CSS paths to xpaths)
-1
$str = '<div class="defaultClass ' . $myclass . '">...</div>';

This assumes myClass is variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.