Organizational Research By

Surprising Reserch Topic

regexp to add attribute in any xml tags

regexp to add attribute in any xml tags  using -'php,xml,regex'

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:

<tag2> some text </tag2>


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

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

asked Oct 11, 2015 by virendra.bajaj
0 votes

Related Hot Questions

2 Answers

0 votes

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) {
echo $xml->asXML();

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

        <![CDATA[Fancy <<SiteName>> [with Breadcrumbs] > in > title]]>

answered Oct 11, 2015 by sujata naik
0 votes

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)

answered Oct 11, 2015 by sameer rathore