Regular Expression Replace in All Files and Subdirs

Recursively search and replace in files using this PHP script. Follows subdirectories and uses regular expressions for search and replace. Allows file extensions to be specified.

<?php
    function recursiveFileReplace ($directory, $search, $replace, $valid_ext = '') {

        // directory is the starting point of the search
        // search is a regular expression
        // replace is the replacement string

        // example: replace <? with <?php
        // recursiveFileReplace('/path-to-files/', '|<\?\s+|', '<?php ', array('php'));
        if (substr($directory, -1, 1) == '/') {
            $directory = substr($directory, 0, strlen($directory) - 1);
        }

        // recursively scan directory and retrieve files
        if ($handle = opendir($directory)) {

            while (false !== ($file = readdir($handle))) {

                if ($file != '..' && $file != '.') {

                    if (is_file($directory. '/' .$file)) {

                        if (is_array($valid_ext)) {

                            $file_ext = strtolower(substr($file, strrpos($file, '.') + 1));
                            if (!in_array($file_ext, $valid_ext)) {
                                continue;
                            }

                        }

                        $contents = file_get_contents($directory. '/' .$file);
                        $contents = preg_replace($search, $replace, $contents);
                        file_put_contents($directory. '/' .$file, $contents);

                    }

                    if (is_dir($directory. '/' .$file)) {

                        recursiveFileReplace($directory. '/' .$file, $search, $replace, $valid_ext);

                    }

                }

            }

            return true;

        }

    }
?>

Comments (0)

Commenting has been disabled for this entry

If you'd like to discuss an aspect of this post, feel free to contact me via email.