Skip to content

Instantly share code, notes, and snippets.

@nikic
Created September 12, 2014 17:41
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nikic/74769d74dad8b9ef221b to your computer and use it in GitHub Desktop.
Save nikic/74769d74dad8b9ef221b to your computer and use it in GitHub Desktop.
Tool for porting alternative PHP tags to <?php, <?= and ?>
<?php
/*
* Note: This script will directly modify the .php files in the given directory.
* It is assumed that the code is under version control, so you can easily review
* the changes using `git diff` or similar.
*/
function usageError() {
die("Usage: php -d asp_tags=1 portAlternativeTags.php dir/\n");
}
if ($argc !== 2) {
usageError();
}
$dir = $argv[1];
if (!is_dir($dir)) {
echo "\"$dir\" is not a directory.\n";
usageError();
}
if (!ini_get('asp_tags')) {
echo "asp_tags must be enabled.\n";
usageError();
}
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($it as $file) {
if (!preg_match('/\.php$/', $file)) {
continue;
}
$code = file_get_contents($file);
$tokens = token_get_all($code);
$tokens = portTags($tokens);
$code = tokensToCode($tokens);
file_put_contents($file, $code);
}
function portTags(array $tokens) {
foreach ($tokens as $i => &$token) {
if ($token[0] === T_OPEN_TAG) {
if (strpos($token[1], '<?') === 0) {
continue;
}
$token[1] = '<?php';
if (!isset($tokens[$i]) || $tokens[$i][0] !== T_WHITESPACE) {
$token[1] .= ' ';
}
} else if ($token[0] === T_OPEN_TAG_WITH_ECHO) {
if ($token[1] === '<?=') {
continue;
}
$token[1] = '<?=';
} else if ($token[0] === T_CLOSE_TAG) {
if (strpos($token[1], '?>') === 0) {
continue;
}
if (preg_match('~^(?:%>|</script\s*>)(\s*)$~', $token[1], $matches)) {
$token[1] = '?>' . $matches[1];
}
}
}
return $tokens;
}
function tokensToCode(array $tokens) {
$code = '';
foreach ($tokens as $token) {
if (is_array($token)) {
$code .= $token[1];
} else {
$code .= $token;
}
}
return $code;
}
@pgl
Copy link

pgl commented Oct 2, 2014

The preg_match() should be case-insensitive: https://gist.github.com/pgl/e28468339344d0bcd91f

@pkordylewski
Copy link

It always adds an additonal whitespace for "<?php". See https://gist.github.com/pkordylewski/3e74126c248f44b7c826

@alixbergeret
Copy link

Hi,

Am I right in saying that this script won't work in PHP7? Since it relies on ASP tags being enabled?

How strange... by definition this script will be used by people who have migrated to PHP7 and want to "fix" old scripts...

Am I missing something?

Cheers!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment