Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snippet to remove comment strings other than phpdoc.
<?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