用REGEX匹配PHP注释构造


Match PHP Comment Constructs with REGEX

我正在尝试编写一个正则表达式,它与单行php注释相匹配,该注释以双正斜杠开始,一直持续到行的末尾。我的正则表达式模式应该匹配双正斜杠之后的每个字符,而Negative Lookbehin构造将匹配限制为换行符之前的每个字符。

目前,regex模式只匹配单行字符串,但当字符串被分解为多个换行符时会失败。我该怎么解决这个问题?

$detail = '//This first line is a comment 
This second line is not a comment.';
function parser($detail) 
{
    if (preg_match('#(//.*)((?<!.)'r'n)$#', $detail)) 
    {
        $errors[] = 'Password should include uppercase and lowercase characters.';
        $detail = preg_replace('#(//.*)((?<!.)'r'n)$#','<span class="com"   style="color:red">$1</span>', $detail);
    return $detail;
    }
}
echo parser($detail);

下面的代码片段回答了我的问题。匹配字符串中以双正斜杠开头、以除换行符以外的任何字符结尾的任何一行。隔离匹配的线作为样式的标记。然后,函数返回完整的字符串,并根据需要设置注释样式。

$detail = '//This line is a comment
This second line is not a comment
This third line is not a comment';
function parser($detail) 
{
    $detail = preg_replace('#//(.*)#','<span style="color:red">//$1</span><br/>', $detail);
    return $detail;
}
echo parser($detail);