2014-10-26 75 views
0

我想写一个正则表达式匹配单行php注释开始双正斜杠并持续到行尾。我的正则表达式模式应该与双向正斜杠后面的每个字符匹配,而负向Lookbehind构造将匹配限制为新换行符之前的每个字符。匹配PHP评论构造与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); 
+2

相关:https://github.com/nikic/PHP-Parser/ – PeeHaa 2014-10-26 20:01:18

+0

如果你只是想匹配,直到行使用'\ V *'或'$#M' – mario 2014-10-26 20:08:42

+0

@mario结束,\ V *只返回行军,我需要返回完整的字符串,并在代码中显示注释部分包裹在span类中。任何想法如何操纵正则表达式来返回? – Terungwa 2014-10-26 20:34:51

回答

0

此代码片段回答了我的问题。匹配以双正斜杠开始并以除新行之外的任何字符结尾的任何一行字符串。将匹配的行隔离为样式的标记。该函数然后返回完整的字符串,并根据需要设置注释样式。

$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);