Removes comments from a PHP source string.
We don't use the PHP php_strip_whitespace() function as we want the content to be readable and well-formatted.
string $source A PHP string:
string The PHP string with the comments removed
public static function stripComments($source) {
if (!function_exists('token_get_all')) {
return $source;
}
$rawChunk = '';
$output = '';
$tokens = token_get_all($source);
for (reset($tokens); false !== ($token = current($tokens)); next($tokens)) {
if (is_string($token)) {
$rawChunk .= $token;
}
elseif (T_START_HEREDOC === $token[0]) {
$output .= preg_replace(array(
'/\\s+$/Sm',
'/\\n+/S',
), "\n", $rawChunk) . $token[1];
do {
$token = next($tokens);
$output .= $token[1];
} while ($token[0] !== T_END_HEREDOC);
$rawChunk = '';
}
elseif (!in_array($token[0], array(
T_COMMENT,
T_DOC_COMMENT,
))) {
$rawChunk .= $token[1];
}
}
// replace multiple new lines with a single newline
$output .= preg_replace(array(
'/\\s+$/Sm',
'/\\n+/S',
), "\n", $rawChunk);
return $output;
}