Regexp to add attribute in any xml tags

Solution 1:

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>