簡體   English   中英

使用REGEX匹配PHP注釋構造

[英]Match PHP Comment Constructs with REGEX

我正在嘗試編寫一個與單行php注釋匹配的正則表達式,該注釋以雙正斜杠開始,一直持續到該行的末尾。 我的正則表達式模式應該匹配雙正斜杠之后的每個字符,並且負向后看構造將匹配限制為新換行符之前的每個字符。

當前,正則表達式模式僅匹配單個行字符串,但是當字符串分成多個換行符時失敗。 我該如何解決?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM