我正在为svn跟踪系统编写代码。我想计算开发人员提出的评论数量。
是否有一个php函数来获取两个字符之间的行数? 我想在/ *和* /
之间获取行数提前感谢。
答案 0 :(得分:1)
您可以使用Tokenizer来解析PHP源文件,然后对注释进行计数。
示例强>
$source = file_get_contents('source.php');
$tokens = token_get_all($source);
$comments = array_filter($tokens, function($token) {
return $token[0] === T_COMMENT;
});
echo "Number of comments: " . count($comments);
请注意,这会计算评论数量,以计算额外计算$token[1]
(实际评论)中换行符所需的行数。
<强>更新强>
我想尝试一下,你走了:
$source = <<<PHP
<?php
/*
* comment 1
*/
function f() {
echo 'hello'; // comment 2
// comment 3
echo 'hello'; /* OK, this counts as */ /* three lines of comments */ // because there are three comments
}
PHP;
$tokens = token_get_all($source);
$comments = array_filter($tokens, function($token) {
return $token[0] === T_COMMENT;
});
$lines = array_reduce($comments, function(&$result, $item) {
return $result += count(explode("\n", trim($item[1])));
}, 0);
echo "Number of comments: ", count($comments), "\n";
echo "Lines of comments: ", $lines;
<强>输出强>
Number of comments: 6
Lines of comments: 8
<强> Online Demo 强>
答案 1 :(得分:0)
您可以使用preg_replace
删除/* */
代码之间的所有内容,然后计算行数。
<?php
$string = <<<END
just a test with multiple line
/*
some comments
test
*/
and some more lines
END;
$lines = explode(chr(10), $string);
echo 'line count: ' . (count($lines)+1) . '<br>';
//line count: 10
$pattern = '/\/\*(.*)\*\//s';
$replacement = '';
$string = preg_replace($pattern, $replacement, $string);
$lines = explode(chr(10), $string);
echo 'line count: ' . (count($lines)+1);
//line count: 6
?>
答案 2 :(得分:0)
作为起点,您可以尝试使用PHP Reflection Library getDocComment(),但可能无法获取内联注释。