I have this string:
$str = '<div class="defaultClass">...</div>';
how do I append 'myClass' next to 'defaultClass' ?
There is no specific function to append a string in PHP. In order to do this task, we have the this operator in PHP: Using Concatenation assignment operator (“. =”): The Concatenation assignment operator is used to append a string str1 with another string str2.
strrpos() - Finds the position of the last occurrence of a string inside another string (case-sensitive) stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive) strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
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();
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With