如何通过regexp去除MySQL的可执行注释

时间:2012-01-13 13:45:31

标签: php regex strip

我需要在mysqldump结果中获取可执行注释的内容,但是对于regexp

/\/\*\!\d+\s+(.*?)\*\//s

并输入如下数据:

/*!50003 text
some text else
/*
comment
also comment
*/
text...
and also text...
*/

我得到错误的结果,因为它只从“文本”到“也注释”行获取数据。如何跳过评论评论? 感谢。

UPD :我不能使用“^”和“$”来标记输入的开始和结束,因为我在输入中有很多可执行语句。

UPD2 :我想要的输出:

text
some text else
/*
comment
also comment
*/
text...
and also text...

并非所有输入如下评论。我认为,这很奇怪,输出的输出相同。

UPD3 : 可执行注释的开始必须是/ *!ANYNUMBER。必须跳过它并且不包括在输出中。可执行注释的结尾只是* /右输出示例在“UPD2”中显示。

2 个答案:

答案 0 :(得分:3)

纯正则表达式无法处理嵌套,但PHP的味道可以使用recursion。使用PCRE_EXTENDED modifier,我们可以有空格和注释:

%(               # opening RE delimiter, group start
  /\*            # comment open marker
    (  [^/*]     # non comment-marker characters
     | /(?!\*)   # '/' not followed by '*', so not a comment open
     | \*(?!/)   # '*' not followed by '/', so not a comment close
     | (?R)      # recursive case
    )*           # repeat any number of times
  \*/            # comment close marker
)%x              # group end, closing RE delimiter, PCRE_EXTENDED

简而言之:

%(/\*([^/*]|/(?!\*)|\*(?!/)|(?R))*\*/)%x

使用中:

<?php

$commentRE = '%(/\*([^/*]|/(?!\*)|\*(?!/)|(?1))*\*/)%';
$doc = <<<EOS

USE database;

/* comment
and a
/* nested comment /* me too */
   now exiting
 */
the comment */


/*!50003 text
some text else
/*
comment
also comment
*/
text...
and also text...
*/

CREATE TABLE IF NOT EXISTS ...

EOS;

preg_match_all($commentRE, $doc, $parts);
var_export($parts[0]);

结果:

array (
  0 => '/* comment
  and a
  /* nested comment /* me too */
     now exiting
   */
  the comment */',
  1 => '/*!50003 text
  some text else
  /*
    comment
    also comment
  */
  text...
  and also text...
*/',
)

答案 1 :(得分:1)

基于这个出色的解决方案,我已经完成了一个PHP正则表达式来删除所有类型的注释(只有注释,而不是引用文本看起来像注释;): Regex to match MySQL comments