用preg_replace替换php中的注释

时间:2014-03-06 15:46:44

标签: php regex

我需要用php中的preg_replace()替换所有块注释。 例如:

/**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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

试试这个

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

答案 2 :(得分:0)

解析PHP代码的最佳方法是使用tokenizer。

然而用正则表达式做这件事并不困难。您必须只跳过所有字符串:

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