find replace text in file with Phing

If you don't want to copy files and just replace a string in the current folder where your files reside, do a reflexive task:

<reflexive>
    <fileset dir=".">
        <include pattern="*.js" />
    </fileset>
    <filterchain>
        <replaceregexp>
            <regexp pattern="SEARCH" replace="REPLACEMENT"/>
        </replaceregexp>
    </filterchain>
</reflexive>

You can replace text inside files using filters. Filters are used inside other file operation tasks such as copy.

I believe the main idea behind filters is that you can have template files with tokens instead of real values and you then substitute the tokens as a part of the copy process.

Quick example: have a database configuration template file stored in a template directory. Then you copy it to the target configuration file using:

<copy file="templates/database.config.php.tpl" tofile="config/database.config.php" overwrite="true">
                <filterchain>
                    <replacetokens begintoken="%%" endtoken="%%">
                        <!-- MySQL TOKENS -->
                        <token key="dbname" value="${db.mysql.dbname}" />
                        <token key="dbhost" value="${db.mysql.host}" />
                        <token key="dbport" value="${db.mysql.port}" />
                        <token key="dbuser" value="${db.mysql.username}" />
                        <token key="dbpassword" value="${db.mysql.password}" />
                    </replacetokens>
                </filterchain>
            </copy>

There are plenty of other filters (e.g. regex search and replace) available. See more about filters in the documentation: http://phing.info/docs/guide/stable/chapters/appendixes/AppendixD2-CoreFilters.html

Tags:

Phing