Last active
November 26, 2020 12:49
-
-
Save imo-tikuwa/4a30346a5d6aae822927ac1d242d305e to your computer and use it in GitHub Desktop.
Snippet to remove comment strings other than phpdoc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* phpdoc以外のコメントを削除する | |
* トルツメが難しいので一旦phpdoc以外のコメントを固有のコメント文字列に置換 | |
* その後、固有のコメント文字列を正規表現で行ごと削除という方法をとっています | |
* | |
* 参考:https://www.php.net/manual/ja/tokenizer.examples.php | |
* | |
* @param string $filepath ファイルパス | |
* @return int|false | |
*/ | |
function trim_comment(string $filepath) | |
{ | |
if (!file_exists($filepath)) { | |
return false; | |
} | |
$source = file_get_contents($filepath); | |
$comment_replaced_source = ''; | |
$replace_marker = '// replace marker'; | |
foreach (token_get_all($source) as $token) { | |
if (is_string($token)) { | |
$comment_replaced_source .= $token; | |
} else { | |
list($id, $text) = $token; | |
switch ($id) { | |
case T_COMMENT: | |
$comment_replaced_source .= $replace_marker; | |
if (strpos($text, '//') === 0) { | |
$comment_replaced_source .= "\n"; | |
} | |
break; | |
default: | |
$comment_replaced_source .= $text; | |
break; | |
} | |
} | |
} | |
$comment_removed_source = preg_replace("|^.*{$replace_marker}.*$\n|m", '', $comment_replaced_source); | |
return file_put_contents($filepath, $comment_removed_source); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment