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

Linda Hamilton
Release: 2024-10-23 10:57:37
Original
247 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!