[Insert Job Title]

PHP, MySQL and Servers.

Monday, 10 February 2014

Cleaning up PHP short-open-tags with Eclipse

One major problem of old/legacy or unmaintained PHP scripts is, that they usually use short-open-tags to enclose PHP code:

<? echo "foobar"; ?>

This used to be common in the old days, but trying to run those scripts on a modern LAMP stack will most likely result in 500-code errors.

Sure you could just enable short_open_tag in the php.ini and it would solve the problem. But even though there are no official hints that it might get deprecated or removed, it is still a bad practice. The Basic Coding Standard by the PHP Framework Interop Group clearly states:

Files MUST use only <?php and <?= tags.

So why should you hold on to bad practices, if you can just easily mass replace them to normal open-tags? Eclipse offers a feature where you can do a project based search & replace, and even use Regular Expression with group matching. Follow the steps below to refactor your (or someones else) code.

Steps to fix under Eclipse (PDT):


1) Select via the "File Navigator" your root project folder

Eclipse File Navigator

2) Go to the menu: "Search" -> "File..."

3) Configure as seen in the screenshot below, type into "Containing text:" the following: <\?($|\s+)


Eclipse Search & Replace in Files



4) Click on the button "Replace..."

5) Again, configure as seen in the screenshot. Type into "With:" the following: <?php$1

Eclipse Regular Expresion Text Matches



6) Click on "OK" -> Done! :)


Basically with that regular expression we just used, you are searching for all "<?" occurrences that are followed by either a newline or white space (tabs, spaces). It will then replace it by "<?php" including the same amount of white spaces (or newline) after. This will ensure we are not breaking the code or changing anything else except the PHP short-open tag.