【问题标题】:preg_match PHP comments excluding if in quotes [duplicate]preg_match PHP注释不包括引号[重复]
【发布时间】:2020-04-02 23:52:43
【问题描述】:

我正在尝试编写一个正则表达式来查找和匹配 PHP 代码文件中的注释文本,到目前为止我所做的一切都很好,但有一个例外:

我的模式:

$pattern='/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/';

它仍然匹配这样的行

$string="//this is not a comment"

$string2="/*this is not a comment */"

我知道我需要在某处添加 (?:^|[^"]+[^"]),但真的不知道如何,甚至有可能避免介于“”之间的任何内容吗?

【问题讨论】:

    标签: php comments preg-match quotes


    【解决方案1】:

    正如您已经看到的,使用正则表达式会很棘手。但是 PHP 已经内置了用于解析自身的函数,例如 token_get_all()

    这是一个简单的测试脚本,它将读取名为foo.php 的假设文件中的 PHP 代码并打印出所有 cmets,而不管注释字符(//#/* */)如何:

    <?php
    $code = file_get_contents('foo.php');
    $tokens = token_get_all($code);
    foreach ($tokens as $token) {
        if (is_array($token)) { // Sometimes the token element will be a single character, like ; . > ! etc.
            if (token_name($token[0]) === 'T_COMMENT' || token_name($token[0]) === 'T_DOC_COMMENT') {
                echo $token[1] . PHP_EOL;           
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 2015-05-06
      • 2013-04-05
      相关资源
      最近更新 更多