2014-03-06 57 views
0

我需要用php中的preg_replace()替換所有塊註釋。 例如:使用preg_replace代替php中的註釋

/**asdfasdf 
fasdfasdf*/ 
echo "hello World\n"; 

對於這一點:

echo "hello World\n"; 

我試圖從這個站點的一些解決方案,但沒有人對我的作品。 我的代碼:

$file = file_get_contents($fileinput); 
$file = preg_replace('/\/\*([^\\n]*[\\n]?)*\*\//', '', $file); 
echo $file; 

我例如輸出是與輸入相同。 Link to my regex test

+0

可能重複[?如何使用PHP來刪除JS評論(http://stackoverflow.com/questions/19509863/how-to-remove-js-comments-using -php) –

+0

我知道但它對我來說不正確。例如,如果我有回聲「/ * asdfasdf * /」它將刪除它並輸出將像回聲「」 –

+0

http://www.php.net/ manual/en/function.php-strip-whitespace.php –

回答

0

試試這個

$file = preg_replace('/^\s*?\/\*.*?\*\//m', '', $file); 
2

使用http://www.php.net/manual/en/function.token-get-all.php

$file = file_get_contents($fileinput); 
$tokens = token_get_all($file); // prepend an open tag if your file doesnt have one 

$plain = ''; 
foreach ($tokens as $token) { 
    if (is_array($token)) { 
     list($number, $string) = $token; 
     if (!in_array($number, [T_OPEN_TAG, T_COMMENT])) { // add all tokens you dont want 
      $plain .= $string; 
     } 
    } else { 
     $plain .= $token; 
    } 
} 
print_r($plain); 

輸出:

echo "hello World\n"; 

這裏是所有PHP標記列表:

http://www.php.net/manual/en/tokens.php

0

解析PHP代碼的最好方法是使用標記器。

但是用正則表達式並不是那麼難。您必須只跳過所有字符串:

$pattern = <<<'EOD' 
~ 
(?(DEFINE) 
    (?<sq> ' (?>[^'\\]++|\\{2}|\\.)* ') # single quotes 
    (?<dq> " (?>[^"\\]++|\\{2}|\\.)* ") # double quotes 
    (?<hd> <<< \s* (["']?)(\w+)\g{-2} \R .*? (?<=\n) \g{-1} ;? (\R|$)) # heredoc like 
    (?<string> \g<sq> | \g<dq> | \g<hd>) 
) 
\g<string> (*SKIP)(*FAIL) | /\* .*? \*/ 
~xs 
EOD; 

$result = preg_replace($pattern, '', $data);