Home >Backend Development >PHP Tutorial >How to Efficiently Remove Comments from PHP Code without Compromising Syntax?
Efficient Removal of PHP Code Comments without Compromising Syntax
To effectively eliminate comments from PHP code while preserving embedded HTML, token_get_all() provides a reliable solution. Here's an example implementation:
<code class="php"><?php $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; ?></code>
This solution assumes both PHP 4 and 5 compatibility. It iterates through the code tokens, skipping any that belong to comment types (including standard comments, documentation comments, and PHP 4-style multiline comments), ensuring that embedded HTML is preserved. The resulting $newStr contains the modified code without comments.
The above is the detailed content of How to Efficiently Remove Comments from PHP Code without Compromising Syntax?. For more information, please follow other related articles on the PHP Chinese website!