正则表达式删除注释和多行注释和空行

Ahm*_*uad 21 php regex preg-replace

我想解析一个文件,我想使用php和正则表达式来剥离:

  • 空白或空行
  • 单行评论
  • 多行评论

基本上我想删除任何包含的行

/* text */ 
Run Code Online (Sandbox Code Playgroud)

或多行注释

/***
some
text
*****/
Run Code Online (Sandbox Code Playgroud)

如果可能,另一个正则表达式来检查该行是否为空(删除空行)

那可能吗?有人可以给我发一个正则那样的正则表达式吗?

非常感谢.

cha*_*aos 45

$text = preg_replace('!/\*.*?\*/!s', '', $text);
$text = preg_replace('/\n\s*\n/', "\n", $text);
Run Code Online (Sandbox Code Playgroud)


Chr*_*utz 11

请记住,如果要解析的文件包含包含符合这些条件的字符串,则您使用的任何正则表达式都将失败.例如,它会变成这样:

print "/* a comment */";
Run Code Online (Sandbox Code Playgroud)

进入:

print "";
Run Code Online (Sandbox Code Playgroud)

这可能不是你想要的.但也许是,我不知道.无论如何,正则表达式在技术上无法以避免该问题的方式解析数据.我在技术上说,因为现代PCRE 正则表达已经加入了许多黑客攻击,使他们都能够做到这一点,更重要的是,不再是正则表达式,而是其他任何东西.如果你想避免在引号或其他情况下剥离这些东西,那么就没有任何东西可以替代完整的解析器(尽管它仍然可以非常简单).


小智 5

//  Removes multi-line comments and does not create
//  a blank line, also treats white spaces/tabs 
$text = preg_replace('!^[ \t]*/\*.*?\*/[ \t]*[\r\n]!s', '', $text);

//  Removes single line '//' comments, treats blank characters
$text = preg_replace('![ \t]*//.*[ \t]*[\r\n]!', '', $text);

//  Strip blank lines
$text = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $text);
Run Code Online (Sandbox Code Playgroud)

  • 当涉及到 URL 时,单行注释替换不起作用。`https://example.com` 也被替换。 (2认同)