1

I'm working with a legacy PHP project that I inherited that had over a thousand files with nothing but includes to other classes. Now that I've refactored it to use composer, and used PHPstorm to remove the references to including the classes, I have over 1200 files with nothing but an opening php tag and a few empty lines.

I was able to use this regex to find them: \<\?php\n^(\s*$){1,}\z

However, when I try to replace that with nothing, or with a string like DELETEME PhpStorm won't actually do the replace.

Is there a way via the command line that I can recursively search for files that contain only an opening PHP tag and empty lines and then delete those files?

Rory
  • 95
  • 8
  • Still not sure if you want to delete the files, or just replace the tags. [This](https://stackoverflow.com/a/15402972/7544655) answer from rezizter should help you. – doriclazar May 25 '17 at 16:37
  • Sorry for being unclear, I want to delete the file. – Rory May 25 '17 at 20:29

1 Answers1

2

You may use a not so well known pattern: \Q...\E. This leaves everything in between as it is, so you don't need to escape any special characters:

\A        # the very start of the string
\Q<?php\E # <?php
\s+       # whitespaces including newlines, at least once
\Q?>\E    # ?>
\Z        # the very end of the string


In PHP with the help of glob() this would be:
<?php
$regex = '~\A\Q<?php\E\s+\Q?>\E\Z~';

foreach (glob("*.php") as $file) {
    $content = file_get_contents($file);
    if (preg_match($regex, $content)) {
        // do sth. here
        // e.g. delete the file
    }
}
?>

See a demo of the regex on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79
  • 1
    Thanks Jan, that was exactly what I needed. I used the RecursiveDirectoryIterator instead of glob and I modified slightly since my files did not have closing tags. I put the solution here in case anyone else ever needs this. https://gist.github.com/rorymcdaniel/8d359ffe457de1dd7765bb7669446ba7 – Rory May 25 '17 at 20:44