Best way to automatically remove comments from PHP code

php remove html comments
phpstorm remove all comments
regex remove comments
notepad++ remove all comments
remove comments from json online
vscode remove all comments
php remove whitespace from file
remove all comments in file

Whats the best way to remove comments from a PHP file?

I want to do something similar to strip-whitespace() - but it shouldn't remove the line breaks as well.

EG:

I want this:

<?PHP
// something
if ($whatsit) {
    do_something(); # we do something here
    echo '<html>Some embedded HTML</html>';
}
/* another long 
comment
*/
some_more_code();
?>

to become:

<?PHP
if ($whatsit) {
    do_something();
    echo '<html>Some embedded HTML</html>';
}
some_more_code();
?>

(Although if the empty lines remain where comments are removed, that wouldn't be ok).

It may not be possible, because of the requirement to preserve embedded html - thats whats tripped up the things that have come up on google.

I'd use tokenizer. Here's my solution. It should work on both PHP 4 and 5:

$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;

Any program to automatically remove comments? - Get Started, 1. use following regexp in find tool to replace all multi-line comments with empty /\​*(\*)? /503871/best-way-to-automatically-remove-comments-from-php-code,  Continue this conversation via emailGet only replies to your comment, the best of the rest, as well as a daily recap of all comments on this post. No more than a few emails daily, which you can reply to/unsubscribe from directly from your inbox. Use Code Editor

How about using php -w to generate a file stripped of comments and whitespace, then using a beautifier like PHP_Beautifier to reformat for readability?

Remove comments from file, Learn how to to remove HTML comments from a page using PHP. Write Better JavaScript with Promises be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. For my use, I'd prefer this being done from an htaccess file – is this possible at all? removing php comments with replace tool using regex in phpstorm How do I remove multiline comments from php files with regex? Best way to automatically remove

$fileStr = file_get_contents('file.php');
foreach (token_get_all($fileStr) as $token ) {
    if ($token[0] != T_COMMENT) {
        continue;
    }
    $fileStr = str_replace($token[1], '', $fileStr);
}

echo $fileStr;

edit I realised Ionut G. Stan has already suggested this, but I will leave the example here

Remove HTML Comments with PHP, WordPress Plugin to deactivate comments functions and remove areas executable file 703 lines (597 sloc) 18.8 KB Maybe other users will refactoring the plugin for better code, that we can also include tests. */ Replace xmlrpc methods. I want to parse a file and I want to use php and regex to strip: blank or empty lines single line comments multi line comments basically I want to remove any line containing /* text */ or multi

Here's the function posted above, modified to recursively remove all comments from all php files within a directory and all its subdirectories:

function rmcomments($id) {
    if (file_exists($id)) {
        if (is_dir($id)) {
            $handle = opendir($id);
            while($file = readdir($handle)) {
                if (($file != ".") && ($file != "..")) {
                    rmcomments($id."/".$file); }}
            closedir($handle); }
        else if ((is_file($id)) && (end(explode('.', $id)) == "php")) {
            if (!is_writable($id)) { chmod($id,0777); }
            if (is_writable($id)) {
                $fileStr = file_get_contents($id);
                $newStr  = '';
                $commentTokens = array(T_COMMENT);
                if (defined('T_DOC_COMMENT')) { $commentTokens[] = T_DOC_COMMENT; }
                if (defined('T_ML_COMMENT')) { $commentTokens[] = T_ML_COMMENT; }
                $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; }
                if (!file_put_contents($id,$newStr)) {
                    $open = fopen($id,"w");
                    fwrite($open,$newStr);
                    fclose($open); }}}}}

rmcomments("path/to/directory");

remove-comments-absolutely/remove-comments-absolute.php at , php_strip_whitespace — Return source with stripped comments and whitespace Returns the PHP source code in filename with PHP comments and whitespace removed. echo php_strip_whitespace(__FILE__); I was looking earlier for a way to strip php comments from my source files but didn't come up with much. There are several ways to add a comment in PHP code. The first is by using // to comment out a line. This one-line comment style only comments to the end of the line or the current code block, whichever comes first.

a version more powerful : remove all comments in the folder

<?php
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
$fileArr = [];
foreach($it as $file){
    if(pathinfo($file,PATHINFO_EXTENSION) == "php"){
        ob_start();
        echo $file;
        $file = ob_get_clean();
        $fileArr[] = $file;
    }
}
$arr = [T_COMMENT,T_DOC_COMMENT];
$count = count($fileArr);
for($i=1;$i < $count;$i++){
    $fileStr = file_get_contents($fileArr[$i]);
    foreach(token_get_all($fileStr) as $token){
        if(in_array($token[0],$arr)){
            $fileStr = str_replace($token[1],'',$fileStr);
        }            
    }
    file_put_contents($fileArr[$i],$fileStr);
}

php_strip_whitespace - Manual, echo 'This is a test'; // This is a one-line c++ style comment /* This is a multi However, I try to keep things consistent in my code that way it's easy for the next person to read. So something like for example, placed at top of file: <?php $​ver3  In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who may view your website's source code. However, PHP's comments are different in that they will not be displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP comments only useful to PHP programmers.

Comments - Manual, comments at the beginning of the file are removed /* Block comments are removed - easy peasy */ https://urls.are.preserved.for.you// and comments after them  Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it's easy for the next person to read.

Remove inline/block comments from code files, Here's a quick way to remove all comments using output buffering and Place the PHP code into your functions.php file inside the WordPress  3 Ways to Remove All Spam and Pending Comments in WordPress Raymond Updated 3 years ago Wordpress 49 Comments Although there are many different content management systems available to use, WordPress remains one of the most popular today and has won a couple of awards such as the Critic’s Choice Best Open Source PHP CMS and People’s Choice

How to remove html comment from source?, Remove HTML comments. <p>Lorem ipsum dolor</p> <!-- sit amet -->. Using the .php extension for all your scripts is not necessary, and in fact can be harmful (by exposing too much information about your server, and by limiting what you can do in the future without breaking links). There are several ways to hide your .php script extension: (1) Don't hard code file types at all.

Comments
  • Look into obfusacators. Although you'd have to find one that was configurable--to strip comments only.
  • Someone is bound to ask why: The code needs to go to a clients server to be deployed, so we want to make sure no is there that shouldn't be.
  • Are you talking about inappropriate content in the comments? Or is this just for size - smaller PHP scripts make almost no performance difference except in high usage or unusual cases (and Zend is usually a better answer than stripping them).
  • its where there are things in the comments that we don't want to risk being read. they shouldn't be there - but too late for that now.
  • I'd be reluctant to remove comments unless you're doing obfuscation. You may find a time when you need those comments on the client's server. Also, have you made it clear to them that the code is coming with comments? They may not like the surprise when they bring in different consultants...
  • You should take out $commentTokens initialization out of the foreach block, otherwise +1 and thanks :)
  • @Raveren, you're damn right. I have no idea what was in my mind back then to put that piece of code inside the loop. Thanks for pointing it out.
  • @lonut Thanks! Very useful :-)
  • @IonuțG.Stan I have been trying to implement this, but it's breaking a lot of code. Here's an example: ``` ### Version ### const MARKDOWNLIB_VERSION = "1.6.0"; ### Simple Function Interface ### public static function defaultTransform($text) { ``` Becomes ``` ### Version # const MARKDOWNLIB_VERSION = "1.6.0"; ### Simple Function Interface # public static function defaultTransform($text) { ``` Not sure if this will format well here...
  • @AndrewChristensen I can't reproduce it. What PHP version are you using?
  • thanks for the suggestion - the other way was quicker to use, as all the bits were already on the server.
  • Yes, I like the tokeniser answer, simpler!
  • Sometimes, the simplest answers are best :)