php正則去掉php註釋

來源:文萃谷 1.48W

php的/* */這種註釋,用正則去掉。請問什麼好的辦法嗎?這個正則應該如何改進?

php正則去掉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) 匹配 // 遇到第一個回車後結束

熱門標籤