php注释了如何检查给定的字符串(代码行)


How to check given string(code line) is php commented?

我读取了php文件,文件内容(一些代码行)以逐行的形式存储在php数组中

我的php文件行数组

$old_line_arr = new array(
                           "define ( 'name', '' );"
                           "//define ( 'age', '' );"   
                           "   //define ( 'ID', '' );"
                           )

我想检查给定的行数组是注释

isComment($old_line_arr[0]){
  echo $old_line_arr[0].'commented';
}

如何编写isComment函数?是否有任何内置的php函数用于检查给定的php,比如是否有注释。

快速且肮脏,可能需要更多针对各种情况的错误处理代码:

$string = "//define('ID', '');";
$tokens = token_get_all("<?php $string");
if ($tokens[1][0] == T_COMMENT) {
    // it's a comment
} else {
    // it's not
}

您可以创建类似的function

function isComment($str) {
    $str = trim($str);
    $first_two_chars = substr($str, 0, 2);
    $last_two_chars = substr($str, -2);
    return $first_two_chars == '//' || substr($str, 0, 1) == '#' || ($first_two_chars == '/*' && $last_two_chars == '*/');
}

示例:echo isComment($old_line_arr[0]) ? 'comment' : 'not a comment';