在多个文件中有条件地替换XML标记

I need to search and replace in multiple xml files. I am looking to write a script to do this job as i have many files to edit. For example,

<search position="after" index="0,1,3" offset="2">
   <![CDATA[
      <?php -- code to be searched -- ?>
           ]]>
</search>
<add>
   <![CDATA[ --code to add here-- ]]>
</add>
I need to change above code to following
<search index="1,2,4">
   <![CDATA[
      <?php -- code to be searched -- ?>
           ]]>
</search>
<add position="after" offset="2">
   <![CDATA[ --code to add here-- ]]>
</add>


I need to

1. move position from search and add tag, position can be 'replace','after','before'.

2. index tag should also be moved to add tag, and incremented as new index starts from 1 instead of zero

3. move offset to add tag

As far as I know Searching for a particular string and replacing is easy using str_replace but i cannot get how to search for a string and replace or append next line and iterating it in all files ending with .xml extension. What is the best way to do it either in php or command line?

Well, first thing to do is to write an XSLT transformation to do this. You really don't want to attempt this at the text level - there are far too many ways of getting it wrong, especially if there are too many files to check each one by hand. The XSLT 2.0 code would be as follows (assuming a wrapper element around search and add which I will call X)

<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="X">
 <xsl:copy>
  <search index="{string-join(for $t in tokenize(search/@index, ',') return string(number($t)+1))}">
    <xsl:copy-of select="search/node()"/>
  </search>
  <add position="{search/@position}" offset="{search/@offset}">
    <xsl:copy-of select="add/node()"/>
  </add>
 </xsl:copy>
</xsl:template>

</xsl:transform>

Then you need to apply this to all files in a directory. If you're using Saxon you can do this from the command line: specify -s:input-dir -o:output-dir.