Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string manipulation: Append html class to a string

Tags:

html

string

php

I have this string:

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

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

like image 406
Alex Avatar asked Jun 28 '10 10:06

Alex


People also ask

How do I append a character to a string in PHP?

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.

How can we search for a text within a string using PHP?

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)


3 Answers

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();
like image 108
Gordon Avatar answered Oct 15 '22 06:10

Gordon


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.

like image 22
Emil Vikström Avatar answered Oct 15 '22 06:10

Emil Vikström


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/

like image 1
RobertPitt Avatar answered Oct 15 '22 06:10

RobertPitt