Function analysis for removing PHP comments and spaces from the PHP file (PHP code compression)

Source: Internet
Author: User
I tried regular expressions myself, but I found that the filtering of single-line comments is not satisfactory and it is easy to make mistakes. I accidentally saw the strip_whitespace function in a sns, and shared it with me. I hope to help my friends who need it. Recently, I learned from thinkphp's 'runtime _ ALLINONE 'experience: I am not afraid of caching a lot, I am afraid that the call will be messy. simply merge all the commonly used files into one file...
The code is as follows:
Function strip_whitespace ($ content ){
$ StripStr = '';
// Analyze the php source code
$ Tokens = token_get_all ($ content );
$ Last_space = false;
For ($ I = 0, $ j = count ($ tokens); $ I <$ j; $ I ++ ){
If (is_string ($ tokens [$ I]) {
$ Last_space = false;
$ StripStr. = $ tokens [$ I];
}
Else {
Switch ($ tokens [$ I] [0]) {
// Filter various PHP comments
Case T_COMMENT:
Case T_DOC_COMMENT:
Break;
// Filter spaces
Case T_WHITESPACE:
If (! $ Last_space ){
$ StripStr. = '';
$ Last_space = true;
}
Break;
Default:
$ Last_space = false;
$ StripStr. = $ tokens [$ I] [1];
}
}
}
Return $ stripStr;
}

This user-defined function effectively solves the problem that php_strip_whitespace does not properly understand the built-in uncomment space function. < Usage
The code is as follows:
$ Str = strip_whitespace ('
We have to splice this before. I don't understand it either. if we don't splice it, the result generated by executing the command is incorrect.
Php_strip_whitespace
String php_strip_whitespace (string $ filename)
If only a single file does not have heredoc, it is recommended to use quick Php_strip_whitespaceFunction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.