Terungwa
Terungwa

Reputation: 427

Match PHP Comment Constructs with REGEX

I am trying to write a regex that matches a single-line php comment starting with a double forward slash and continuing until the end of the line. My regex pattern is supposed to match every character after the double forward slash and the Negative Lookbehind construct limits the match up to every character preceding a new line break.

Currently, the regex pattern only matches single line strings, but fails when the string is broken into multiple line breaks. How may I fix this?

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

Upvotes: 0

Views: 118

Answers (1)

Terungwa
Terungwa

Reputation: 427

This code snippet below answered my question. Match any line of a string beginning with a double forward slash and ends with any character except new line. Isolate the matched line as a token for styling. The function then returns the full string with the comment styled as needed.

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

Upvotes: 0

Related Questions