Question

I'm trying to match the class attribute of <html> tag and to add a class name using preg_replace().
Here is what I tried so far:

$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/< *html[^>]*class *= *["\']?([^"\']*)/i';
if(preg_match($pattern, $content, $matches)){
    $content = preg_replace($pattern, '<html class="$1 my-custom-class">', $content);
}
echo htmlentities($content);

But, I got only this returned:

<!DOCTYPE html><html class="dummy my-custom-class">"><head></head><body></body></html>

The attribute lang="en" is dropped out and the tag is appended with the duplicates like ">">. Please help me.

Was it helpful?

Solution

Please try this code it works, perfectly well :)

<?php

$content = '<!DOCTYPE html><html lang="en" class="dummy"><head></head><body></body></html>';
$pattern = '/(<html.*class="([^"]+)"[^>]*>)/i';

$callback_fn = 'process';

$content=preg_replace_callback($pattern, $callback_fn, $content);


function process($matches) {

$matches[1]=str_replace($matches[2],$matches[2]." @ My Own Class", $matches[1]);

return $matches[1];

}


echo htmlentities($content);

?>

OTHER TIPS

Remove the * in pattern for regex way

Use this pattern

/<html[^>]*class *= *["\']?([^"\']*)/i

I suggest use Dom parser for parsing the html

<?php
libxml_use_internal_errors(true);
$html="<!DOCTYPE html><html lang='en' class='dummy'><head></head><body></body></html>";

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


foreach ($dom->getElementsByTagName('html') as $node) {

    $node->setAttribute('class','dummy my-custom-class');

}

$html=$dom->saveHTML();
echo $html;

OUTPUT:

<!DOCTYPE html>
<html lang="en" class="dummy my-custom-class"><head></head><body></body></html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top