For efficient code maintenance and readability, it's often necessary to remove comments from PHP files. This can be a tedious process, but there are effective solutions available to streamline the task.
Utilizing PHP's tokenizer offers a comprehensive approach to removing comments while preserving embedded HTML. Here's a detailed implementation:
$fileStr = file_get_contents('path/to/file');
$newStr = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT')) {
$commentTokens[] = T_DOC_COMMENT; // PHP 5
}
if (defined('T_ML_COMMENT')) {
$commentTokens[] = T_ML_COMMENT; // PHP 4
}
$tokens = token_get_all($fileStr);
foreach ($tokens as $token) {
if (is_array($token)) {
if (in_array($token[0], $commentTokens)) {
continue;
}
$token = $token[1];
}
$newStr .= $token;
}
echo $newStr;
This solution produces the desired output by removing all comments while preserving the original code structure and embedded HTML. It caters to both PHP 4 and PHP 5 environments. By iterating through the tokens and selectively skipping comment tokens, the solution efficiently extracts the relevant code snippets.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3