ben*_*ley 48 php comments strip
什么是从PHP文件中删除注释的最佳方法?
我想做类似strip-whitespace()的东西 - 但它也不应该删除换行符.
例如:
我要这个:
<?PHP
// something
if ($whatsit) {
do_something(); # we do something here
echo '<html>Some embedded HTML</html>';
}
/* another long
comment
*/
some_more_code();
?>
Run Code Online (Sandbox Code Playgroud)
成为:
<?PHP
if ($whatsit) {
do_something();
echo '<html>Some embedded HTML</html>';
}
some_more_code();
?>
Run Code Online (Sandbox Code Playgroud)
(虽然如果删除注释的空行仍然存在,那就不行了).
这可能是不可能的,因为需要保留嵌入式HTML - 这就是在谷歌上出现的东西绊倒了.
Ion*_*tan 55
我会使用tokenizer.这是我的解决方案.它应该适用于PHP 4和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;
Run Code Online (Sandbox Code Playgroud)
$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;
Run Code Online (Sandbox Code Playgroud)
编辑 我意识到Ionut G. Stan已经提出过这个建议,但我会在这里留下这个例子
小智 9
这是上面发布的函数,修改为递归删除目录及其所有子目录中所有php文件的所有注释:
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");
Run Code Online (Sandbox Code Playgroud)
小智 5
更强大的版本:删除文件夹内所有评论
<?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);
}
Run Code Online (Sandbox Code Playgroud)