PHP的/* */這種註釋,用正則去掉。請問什麼好的辦法嗎?這個正則應該如何改進?
檔案:
<?php
/**
* 加法計算
* 測試
*/
// 設定$a的.值
$a = 10;
// 設定$b的值
$b = 5;
// 加法
$c = $a + $b;
# 輸出結果
echo $c;
檔案:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
echo "原始碼:<br />";
show_source('./');
echo "<hr />去除註釋後:<br />";
highlight_string(removeComment(file_get_contents('./')));
/**
* 去除PHP程式碼註釋
* @param string $content 程式碼內容
* @return string 去除註釋之後的內容
*/
function removeComment($content){
return preg_replace("/(/*.**/)|(#.*?n)|(//.*?n)/s", '', str_replace(array("rn", "r"), "n", $content));
}
測試輸出
執行,輸出如下:
正則分析
?
1
2
3
(/*.**/) 匹配 /* */
(#.*?n) 匹配 # 遇到第一個回車後結束
(//.*?n) 匹配 // 遇到第一個回車後結束