删除评论之间的文本

时间:2013-07-28 11:44:59

标签: php regex preg-replace

为了发送查询以使用JDBC执行,我必须删除/ *和* /

之间的texte
/*==============================================================**/
/* Description : ... */
/* Author   : rgosse                                                  */
/* Date de création du script : 25/04/2013                    */
/*==============================================================*/

/*==============================================================*/
/* PISTE D'AUDIT                                                */
/*==============================================================*/
declare @username varchar(25)
declare @dateNow datetime
declare @contact_id numeric
...

我可以用preg_replace吗?

喜欢

preg_replace("/[/*][^*\/]+\[*/]/","", $sql);

3 个答案:

答案 0 :(得分:2)

您可以使用此模式

$code = preg_replace('~/\*(?>[^*]++|\*++(?!/))*\*++/~', '', $code);

详细说明:

~              # delimiter (instead of /, avoid to escape all the / in the pattern)
/              # literal /
\*             # literal * (must be escaped since it's a special character)
(?>            # open a non capturing group (atomic)
    [^*]++     # all characters except * one or more times
  |            # OR
    \*++(?!/)  # * one or more times not followed by /
)*             # repeat the group zero or more times (here * is a quantifier)
\*++           # * one or more times
/              # literal /
~              # pattern delimiter

答案 1 :(得分:0)

你需要逃避/*这样的字符,因为它们具有特殊意义,你只能在一个地方完成它。下面的代码应该可以解决问题

 preg_replace("^/\/\*[^*\/]+\*\/$/","", $sql);

答案 2 :(得分:0)

要替换我们需要匹配开头和结尾注释的注释之间的文本,然后替换它们之间的元素。由于*是一个quanitifer,我们需要将其转义为\*,因此它的自然行为不会在PHP中引发错误。

注意: 在下文中,我假设平衡的评论标记。

$code = "
/*==============================================================**/
/* Description : ... */
/* Author   : rgosse                                                  */
/* Date de création du script : 25/04/2013                    */
/*==============================================================*/

/*==============================================================*/
/* PISTE D'AUDIT                                                */
/*==============================================================*/
declare @username varchar(25)
declare @dateNow datetime
declare @contact_id numeric
";

$pattern = "!(/\*).+(\*/)!";
$replacement = '/**/';

$newCode = preg_replace($pattern,$replacement,$code);

echo $newCode;

<强>输出:

/**/
/**/
/**/
/**/
/**/

/**/
/**/
/**/
declare @username varchar(25)
declare @dateNow datetime
declare @contact_id numeric

如果您想完全替换所有评论,请进行以下更改:

$replacement = '';
相关问题