I'm updating some old code, and noticed there's a lot of files that still have the old-style PHP file ending, where the ?>
is the last chars in the file.
NOTE: this is in keeping with many coding standards for PHP eg.: http://www.php-fig.org/psr/psr-2/
Is there a way to quickly remove these directory wide (via preg_replace
, maybe grep
/ sed
, or whatever) but not remove legitimate closing tags in in-line PHP blocks?
I have no problem finding / replacing these-- I am not sure how to ensure that it's the last characters in the file though.
Thanks
Firstly, as with all bulk search and replace tasks, be sure you have backed up the files so you have something to fall back on in case this doesn't work.
Then, on the command line, try:
$ sed -i '$s/\([[:blank:]]\)*?>\([[:blank:]]\)*$//g' "$(grep -rl '^\([[:blank:]]\)*?>\([[:blank:]]\)*$')"
$()
containing a grep command-r
to recursively find files. If your directory has mixed in non-PHP files and takes too long, we can work in a find
, however for now try this-l
to just list, don't show the match, thus pass file names to sed
command[:blank:]
is a POSIX character class to match space or tabs.?>
, followed by space or tab zero+ characters, then end of line.?>
but for whatever odd reason you happen to have extra white spaces before and after the ?>
?>
on its own line in the middle of the PHP script, so to focus only on end-of-file, last line, we have the sed
-i
replaces in place. Could also have used -i.bak
to automatically have sed create a *.bak
file backup, but I prefer not to clutter the web server with *.bak
files, and if you followed my recommendation to backup prior to this, you already have a backup and won't need this$
specifies the address is the last lineAll PHP files MUST end with a single blank line.
requirementdos2unix
on the PHP files and then re-try this commandThe result is the successful elimination of last line ?>
, even if there were extra "unclean" spaces before or after ?>
.
I faced very similar issue recently. In order to fix this I decided to replace content of .php files in Notepad++.
1) Firstly backup all your files in working directory 2) Secondly use following regex in notepad++ to replace all .php files:
(?s)\A(\s+)?<\?(php)?(.*?)\?>(\s+)?\Z
Replace it with:
<?\2\3
It matches all files starting with <?
or <?php
and ending with ?>
. Additionally it removes white spaces before and after tags. If you do not want this behavior to appear, remove the (\s+)?
part from regex.
\A - means beginning of file \s - matching white spaces \Z - means end of file .*? - match everything between tags