Short tags is a topic of some controversy in coding circles: wrapping your script in less-than, question-mark x 2, greater-than signs is easy to type and flows off the fingers but can be a source of confusion to some parsers. In PHP, it is not recommended, but there is a “shorttag” option available to override it globally or locally.
I recently was asked to edit some older PHP code and found it was littered with short tags, both the <? script goes here ?> variety and the shortcut output <?=”Print this string”?> variety, which need to be replaced by <?php script goes here ?> and <?php echo “Print this string” ?> respectively. A bit beyond my search-and-replace regex or sed skills, I found a fairly elegant solution on StackOverflow, which uses PHP to rewrite PHP:
#! /usr/bin/php <?php global $argv;
$contents = file_get_contents($argv[1]) or die; $tokens = token_get_all($contents); $tokens[] = array(0x7E0F7E0F,"",-1);
foreach($tokens as $ix => $token) { if(is_array($token)) { list($toktype, $src) = $token; if ($toktype == T_OPEN_TAG) { if (($src == "<?") && ($tokens[$ix+1][0] != T_STRING)) { $src = "<?php"; if ($tokens[$ix+1][0] != T_WHITESPACE) { $src .= " "; } } } else if($toktype == T_OPEN_TAG_WITH_ECHO) { $src = "<?php echo"; if($tokens[$ix+1][0] != T_WHITESPACE) { $src .= " "; } } print $src; } else { print $token; } }
It just needed a little shell wrapper to take in all the files (which I’d renamed *.php.old and archived and made a backup of) and put them out as *.php.old.new. Again, a quick rename and I was in business. I was astounded to find it ran the first time!
#! /bin/bash
FILES=./*.php.old for f in $FILES do echo "phpize $f >$f.new" ./phpize.php $f>$f.new done