Effective Comment Removal from PHP Code
The task of removing comments from PHP code is often encountered when streamlining code or analyzing its structure. To achieve this, various approaches can be explored. This question-and-answer article delves into an effective solution that maintains the integrity of embedded HTML within the code.
Solution Using Tokenizer
For a comprehensive and efficient comment removal, the answer proposes utilizing token_get_all() in conjunction with predefined comment tokens. This method works flawlessly on both PHP 4 and 5 versions.
<code class="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 approach iterates over each token in the PHP code file while excluding comment-related tokens. As a result, the output $newStr contains only the desired code without comments, preserving embedded HTML intact.
The above is the detailed content of How to Effectively Remove Comments from PHP Code while Preserving Embedded HTML?. For more information, please follow other related articles on the PHP Chinese website!