Skip to content

Instantly share code, notes, and snippets.

@jankkhvej
Forked from anonymous/shellcommand.sh
Created August 1, 2011 06:52
Show Gist options
  • Save jankkhvej/1117678 to your computer and use it in GitHub Desktop.
Save jankkhvej/1117678 to your computer and use it in GitHub Desktop.
script to parse PHP short open tags and convert ones to normal
find project/dir/ -type f -iname "*.php" -exec php -d short_open_tag=On the_script.php {} \;
<?php
$file=$argv[1];
echo "Replacing short open tags in \"$file\"...";
$content = file_get_contents($file);
$tokens = token_get_all($content);
$output = '';
foreach($tokens as $token) {
if(is_array($token)) {
list($index, $code, $line) = $token;
switch($index) {
case T_OPEN_TAG_WITH_ECHO:
$output .= '<?php echo ';
break;
case T_OPEN_TAG:
$output .= '<?php ';
break;
default:
$output .= $code;
break;
}
}
else {
$output .= $token;
}
}
@jchook
Copy link

jchook commented Oct 3, 2021

Thanks. I ended up using this to upgrade my short_open_tag code to be PHP 8 compatible.

#!/usr/bin/env php
<?php

if (!ini_get('short_open_tag')) {
  echo "Please enable short_open_tag before running this migration";
  exit(1);
}

for ($ii = 1; $ii < $argc; $ii++) {

  $file=$argv[$ii];
  echo $file . "\n";

  $content = file_get_contents($file);
  $tokens = token_get_all($content);
  $output = '';
  $changed = false;

  foreach($tokens as $token) {
    if(is_array($token)) {
      list($index, $code, $line) = $token;
      switch($index) {
      case T_OPEN_TAG:
        if (trim($code) === '<?') {
          $output .= '<?php';
          $changed = true;
        } else {
          $output .= $code;
        }
        break;
      default:
        $output .= $code;
        break;
      }

    }
    else {
      $output .= $token;
    }
  }

  if ($changed) {
    // echo $output;
    file_put_contents($file, $output);
  }
}

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