Tip: Replacing Starting Short Tags (Regex)

So, I love using the PHP Short Tags <?. They make my code look prettier and more clear. Also I just dislike repeating “php” everywhere in my code. But alas when I upgrade the PHP version on my Linode server I get errors. So I decided to replace them with the default <?php.

I don’t know much about regex but I was able to cobble together this little regular expression after some trial and error and it seems to catch most, if not all, of the situations while ignoring <?php and <?xml and of course <?=. It also catches those tags that are on their own lines.

Here it is: ((<\?[^phpxml=])|(<\?$))

I use VS Code so I searched my code with the above while making sure I enabled the regex option in the search panel. Hope it’s helpful to someone.

BTW: If you’re on a Mac and you need a good regex tool to help you build and test these, check out RegExRX on the Mac App Store. Really handy.

1 Like

Pretty sure short_open_tag = On would’ve helped here (depending on your PHP version for sure) :smiley:

Haha, it does but I got tired of having to remember to change that each time I do a major upgrade or move to a new computer because the issue isn’t always obvious. Thanks though. :slight_smile:

Afaik it’s deprecated too.

Btw I love to use regex101.com to test and refine my regular expressions.

1 Like

That’s what I use as well.

Short open tags are really not recommended, even if you like them. Also, it’s just a matter of typing php + tab and the tags should be written for you when you have enabled these snippets in the editor.

And alll sort snippets for recurring pieces of code are helpful as well. You always forget what the plugin wrapper syntax looks like? Or the syntax for a controller, for routes? Create a snippet for it…

I like this tool for the purpose: https://snippet-generator.app/