phpregexreplacephp-shorttagsshorttags

Search and replace all php_short_tag that is <?= and <?


I did not want the hasle of turning on php_short_tag in php.ini and also i wanted to use xml without issues which short tags could introduce, so instead i replaced every occurance of a short tag in the code by using search and replace.

I thought i should share it here since i found many answers that did not work until i tweaked them

  1. First search and replace <?= with <?php NOTE: make sure <?php has a space after it so that <?=code will be <?php code and not <?phpcode.

  2. The regex for that is <[?][\=](?!php), check it out at debuggex.com

  3. Then search and replace <? with <?php NOTE: make sure <?php has a space after it so that <?code will be <?php code and not <?phpcode.

  4. The regex for that is <[?](?!php), check it out at debuggex.com


Solution

  • Just make the = symbol as optional one.

    preg_replace('~<\?=?(?!php\b)~', '<?php ', $str);
    

    OR

    preg_replace('~<\?=?(?!php\b)(\w)~', '<?php \1', $str);
    

    DEMO