Regular expression to add namespace to xml tag

If you need to add namespace to xml tag, ie:

<Identifier>ID</Identifier>
<Source>SOURCE</Source>

becomes:

<dc:identifier>ID</dc:identifier>
<dc:source>SOURCE</dc:source>

in php you can use preg_replace_callback function in this manner:

$xmlWithNamespace = preg_replace_callback('|<(/?)(?P<tag>[^>]*)>|m', 'addNamespace', $xml);

// $matches[0]: entire xml tag (ie: <Source> or </Source>), $matches[1]: / or empty, $matches[2] or ['tag']: tag name
function addNamespace($matches) {
    // if it has already namespace, I return without modif
    if(strpos($matches['tag'], ':') !== false)
        return $matches[0];
    $namespace = 'dc:';
    $tag = $namespace . strtolower($matches['tag']);
    return '<' . $matches[1] . $tag . '>';
}

Commenti