Although there are already php_strip_whitespace methods in PHP5 to return the PHP source function after removing comments and spaces, in order to learn, here is a way to provide your own, you can also remove the blanks in the code and comments, the code is as follows:
Copy Code code as follows:
/**
* Remove whitespace and annotations from the code
* @param string $content code content
* @return String
*/
function Strip_whitespace ($content) {
$stripStr = ';
Analyze PHP Source code
$tokens = Token_get_all ($content);
$last _space = false;
for ($i = 0, $j = count ($tokens); $i < $j; $i + +) {
if (is_string ($tokens [$i])) {
$last _space = false;
$stripStr. = $tokens [$i];
} else {
Switch ($tokens [$i][0]) {
Filter various PHP annotations
Case T_comment:
Case T_doc_comment:
Break
Filter spaces
Case T_whitespace:
if (! $last _space) {
$stripStr. = ';
$last _space = true;
}
Break
Case T_start_heredoc:
$stripStr. = "<<<think\n";
Break
Case T_end_heredoc:
$stripStr. = "think;\n";
for ($k = $i +1; $k < $j; $k + +) {
if (is_string ($tokens [$k]) && $tokens [$k] = = '; ') {
$i = $k;
Break
else if ($tokens [$k][0] = = T_close_tag) {
Break
}
}
Break
Default
$last _space = false;
$stripStr. = $tokens [$i][1];
}
}
}
return $stripStr;
}