Brooklyn Nicholson
Brooklyn Nicholson

Reputation: 646

Use regex to add prefixes to HTML classes & ID's?

Kind of an add-on to: There a quick way to add prefixes to all CSS classes & ID's?

I need to find and replace strings like:

id="xyz"

to replace them to id="prefix_xyz"

This becomes tricky with:

class="one two three"

where they all still need a prefix. Any ideas? Thanks!

Upvotes: 3

Views: 888

Answers (1)

hakre
hakre

Reputation: 197692

Do so by search and replace for all id and class values Demo:

$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DomXpath($dom);

$res = $xpath->query('//@class|//@id');
foreach($res as $attr)
{
    $value = explode(' ', $attr->value);
    foreach($value as &$set)
    {
        $set = 'prefix_'.trim($set);
    }
    unset($set);
    $attr->value = implode(' ', $value);
}

echo $dom->saveHTML();

Upvotes: 4

Related Questions