Home >Backend Development >PHP Tutorial >How to Efficiently Remove Comments from PHP Code without Compromising Syntax?

How to Efficiently Remove Comments from PHP Code without Compromising Syntax?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 10:57:37323browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn