PHP 內建 php_strip_whitespace() 僅支援文件路徑,無法直接處理字串變數。ThinkPHP 框架內建 strip_whitespace() 解決此限制,原理是使用 token_get_all() 詞法分析。
<?php
/**
* 移除 PHP 代碼字串中的空白字符與註解
* @param string $content PHP 代碼字串
* @return string 處理後的精簡代碼
*/
function strip_whitespace(string $content): string {
$stripStr = '';
$tokens = token_get_all($content);
$lastSpace = false;
foreach ($tokens as $token) {
if (is_string($token)) {
// 單字符 token(如 ; { } ( ) , 等)
$stripStr .= $token;
$lastSpace = false;
} else {
// [token_id, token_content, line_number]
list($id, $text) = $token;
switch ($id) {
case T_COMMENT: // // 註解、# 註解
case T_DOC_COMMENT: // /** 文檔註解 */
// 直接丟棄
break;
case T_WHITESPACE: // 空白、換行、Tab
if (!$lastSpace) {
$stripStr .= ' '; // 連續空白壓縮為單個空格
$lastSpace = true;
}
break;
case T_START_HEREDOC: // <<
?>