Yann Milin
Yann Milin

Reputation: 1355

Regexp to add attribute in any xml tags

I have well-formed xml documents into string variables. I want to use preg_replace to add a defined attribute to every xml tags.

For example replace:

<tag1>
<tag2> some text </tag2>
</tag1>

by:

<tag1 attr="myAttr">
<tag2 attr="myAttr"> some text </tag2>
</tag1>

So I basically need the regex expression to find any start tags and add my attribute, but I'm a complete regex noob.

Upvotes: 4

Views: 3186

Answers (3)

Yann Milin
Yann Milin

Reputation: 1355

OK, for those reading these lines and are still interested about using the regex way for some reasons, here is how to do it:

$xml_data= preg_replace('/(<[A-Za-z0-9\-\_]+[^>]*)>/u','\1 attr="myAttr">',$xmlData);

But, as discussed earlier, use that one with caution! Use it only on XML source that you know won't be broken (see soulmerge post about that)

Upvotes: 0

soulmerge
soulmerge

Reputation: 75724

Don't use regular expressions for working on xml. Xml is not a regular language. Use the xml extensions of php instead:

$xml = new SimpleXml(file_get_contents($xmlFile));
function process_recursive($xmlNode) {
    $xmlNode->addAttribute('attr', 'myAttr');
    foreach ($xmlNode->children() as $childNode) {
        process_recursive($childNode);
    }
}
process_recursive($xml);
echo $xml->asXML();

All answers containing regular expressions will break this valid xml, for example:

<?xml version="1.0" encoding='UTF-8'?>
<html>
    <head>
        <!-- <meta> ... </meta> -->
        <script>//<![CDATA[
            function load() {document.write('<tt>Test</tt>');}
        //]]></script>
        <title><![CDATA[Fancy <<SiteName>> [with Breadcrumbs] > in > title]]></title>
    </head>
    <body onload="load()">
        <input
            type="submit"
            value="multiline
                   button
                   text"
        />
    </body>
</html>

Upvotes: 13

mschmidt42
mschmidt42

Reputation: 1095

$xml_data = preg_replace("/<([^\/]+\w+)/", "<\\1 attr=\"myAttr\">", $xml_data);

Upvotes: 0

Related Questions