Replace the contents of the tag with a specific class

I am looking for a suitable replacement code that allows me to replace the contents inside any HTML tag that has a specific class, for example.

$class = "blah";
$content = "new content";
$html = '<div class="blah">hello world</div>';

// code to replace, $html now looks like:
// <div class="blah">new content</div>

Mention that:

  • It will not necessarily be a div, it may be <h2 class="blah">
  • A class can have more than one class and still need to be replaced, for example. <div class="foo blah green">hello world</div>

I think regular expressions should be able to do this if I am not open to other suggestions, such as using the DOM class (although I would prefer to avoid this if possible, because it should be compatible with PHP4).

+1
source share
3 answers

HTML. DOMDocument - simple_html_dom:

require_once("simple_html_dom.php");

$class = "blah";
$content = "new content";
$html = '<div class="blah">hello world</div>';

$doc = new simple_html_dom();
$doc->load($html);

foreach ( $doc->find("." . $class) as $node ) {
    $node->innertext = $content;
}

, PHP4. DOMDocument, .

function DOM_getElementByClassName($referenceNode, $className, $index=false) {
    $className = strtolower($className);
    $response  = array();

    foreach ( $referenceNode->getElementsByTagName("*") as $node ) {
        $nodeClass = strtolower($node->getAttribute("class"));

        if (
                $nodeClass == $className || 
                preg_match("/\b" . $className . "\b/", $nodeClass)
            ) {
            $response[] = $node;
        }
    }

    if ( $index !== false ) {
        return isset($response[$index]) ? $response[$index] : false;
    }

    return $response;
}

$doc = new DOMDocument();
$doc->loadHTML($html);

foreach ( DOM_getElementByClassName($doc, $class) as $node ) {
    $node->nodeValue = $content;
}

echo $doc->saveHTML();
+1

, $html HTML-, HTML XML, XML-.

Regex - :

$html = preg_replace('/(<[^>]+ class="[^>]*' . $class . '[^"]*"[^>]*>)[^<]+(<\/[^>]+>)/siU', '$1' . $content . '$2', $html);

, . , , .;)

: " "...;)

2: RegEx:

<?php

$class = "blah";
$content = "new content";
$html = '<div class="blah test"><h1><span>hello</span> world</h1></div><div class="other">other content</div><h2 class="blah">remove this</h2>';

$html = preg_replace('/<([\w]+)(\s[^>]*class="[^"]*' . $class . '[^"]*"[^>]*>).+(<\/\\1>)/siU', '<$1$2' . $content . '$3', $html);

echo $html;

?>

, , "" , "tooMuchBlahNow". , . Btw: , RegEx?;)

-1

There is no need to use the DOM class, it will probably be done the fastest with jQuery, as Khnle said, or you can use the preg_replace () function. Give me some time, I can write a quick regex for you.

But I would recommend using something like jQuery so that you can quickly serve the page to the user and let the computer do the processing instead of your server.

-2
source

All Articles