我正在寫與用PHP編寫的,我的網站語法高亮(用於Ruby)的一個Ruby代碼中,我可以得到它的顏色實例變量,註釋,符號和全局變量,以便遠,但我已經使用下面的正則表達式匹配雙引號字符串時,遇到了一個問題,這裏是我的代碼:正則表達式:匹配非轉義雙引號的字符串
<?php
function codebox($code, $name="", $highlighted_line = -1)
{
echo '<table class="code_table">';
echo '<tr>';
echo '<td class="code_table_header"></td>';
echo '<td class="code_table_name">$name</td>';
echo '<td class="code_table_header"><a href="" class="copy_to_clipboard_link">copy to clipboard</a></td>';
echo '</tr>';
$oddity = 'even';
$line_number = 1;
foreach(preg_split('/(\r?\n)/', $code) as $line)
{
echo '<tr>';
if($line_number % 10 == 0)
{
echo '<td class="line_number" style="font-weight:bold;">' . $line_number . '</td>';
} else {
echo '<td class="line_number">' . $line_number . '</td>';
}
if($line_number == $highlighted_line)
{
echo '<td class="selected_code_cell" colspan="2">' . syntax_highlight($line) . '</td>';
} else {
echo '<td class="' . $oddity . '_code_cell" colspan="2">' . syntax_highlight($line) . '</td>';
}
echo '</tr>';
$line_number += 1;
if($oddity == 'even')
{
$oddity = 'odd';
} else {
$oddity = 'even';
};
};
};
function syntax_highlight($code)
{
// Make it so html doesn't bodge up
$code = htmlentities($code);
// Replace tabs with 4 none blocking spaces
$code = str_replace(' ', ' ', $code);
//instance variables
$code = preg_replace('/\B(\@\w*\S)/', '<span style="color:lime;">$1</span>', $code);
//global variables
$code = preg_replace('/\B(\$\w*\S)/', '<span style="font-weight:bolder;color:#00b0f0;">$1</span>', $code);
//symbols
$code = preg_replace('/\B(\:\w*\S)/', '<span style="color:yellow;">$1</span>', $code);
//strings (double quote)
$code = preg_replace('/"(?:\.|(\\\")|[^\""\n])*"/', '<span style="font-style:italic;color:#FF5A00;">$1</span>', $code);
//strings (single quote)
//$code = preg_replace('/\'(?:\.|(\\\')|[^\'\'\n])*\'/', '<span style="font-style:italic;color:#FF5A00;">$1</span>', $code);
return $code;
};
?>
出於某種原因,雙引號的字符串打破了其他的並沒有進行語法高亮顯示,並有誰知道爲什麼?在此先感謝,埃爾。
你確定你應該只捕獲雙和單引號?正則表達式就是這樣。 – stillstanding 2010-11-07 13:52:19