我想删除一些PHP代码中的所有单行注释,比如使用Visual Basic的代码:

<?php
some code
// "(\/\/[^;)]*)(?=\?\>)"         <-- NOT REMOVED
/* a first comment */
/* a second comment with some // inside
// a single line ; comment inside         <-- NOT REMOVED
// a comment with a ; website http://www.google.com         <-- NOT REMOVED
a third comment
*/
/* a fourth comment with some // inside */
/* a fifth comment with some ftp://ftp.google;com//onefolder inside */
some code
if {// a comment         <-- NOT REMOVED
    doit();
} /* another comment */
some more code// a comment         <-- NOT REMOVED
some more code2// a comment         <-- NOT REMOVED
?>
<?php  // a comment with a website http://www.google.com ?>
<?php and some more code // and a comment ?>
<?php var = 'http://www.google;com'; // and a comment ?>
<?php var = 'https://www.google;com'; // and a comment ?>
<?php var = 'ftp://www.google;com'; // and a comment ?>
<?php var = 'ftp://www.google;com'; // a comment with a website http://www.google.com ?>
<?php var = 'ftp://www.google;com'; // a comment ?         <-- NOT REMOVED
?>

我目前使用的是"(\/\/[^;)]*)(?=\?\>)"模式,这在一定程度上是可行的,但我仍然有剩余的行(参见<-- NOT REMOVED标记).我没有成功地告诉正则表达式删除,直到它找到一个?>序列,在行尾之前是if it is there

你能帮我改进这个正则表达式吗?

因此,它给出了这个(或根据剩余的\n和注释清理后留下的倍数空格,我可以在下一次清理中删除):

<?php
some code  

/* a first comment */
/* a second comment with some // inside <-- END CAN BE REMOVED, NO PROBLEM
  

a third comment
*/
/* a fourth comment with some // inside */ <-- CAN BE REMOVED IF THE ENDING */ IS KEPT
/* a fifth comment with some ftp://ftp.google;com//onefolder inside */
some code
if {
    doit();
} /* another comment */
some more code
some more code2
?>
<?php ?>
<?php and some more code ?>
<?php var = 'http://www.google;com'; ?>
<?php var = 'https://www.google;com'; ?>
<?php var = 'ftp://www.google;com'; ?>
<?php var = 'ftp://www.google;com'; ?>
<?php var = 'ftp://www.google;com'; 
?>

注意:如果这会导致一个编译器可读的代码,那么我在多次传递中这样做没有问题.

推荐答案

扩展样本输入后:

*(?<!:)//(?:.*?)(?= ?\*\/| ?\?>|$)

基本上,这取决于您希望如何防范URL(包含//)--我将在//之前"查找":.作为后续(非正则表达式)替换,您可能希望清除所有延迟的<?php ?>行.

此模式在注释开始之前占用零个或多个空格,但在*/,?>之前留下一个潜在空格

enter image description here

Php相关问答推荐

未找到laravel cascadeOnEdit

未在moodle上运行的计划任务

在函数内部获取一致的单选按钮值以更新WordPress用户数据

在ShipStation for WooCommerce中使用自定义订单项目元数据

Msgraph-sdk-php v2如何从返回对象中获取数据?

Laravel 10 -扩展现有的artisan命令?

Laravel;Composer安装突然返回选项快捷方式不能为空.

如何限制WordPress自定义分类术语页面中的术语数量

在PHP中读取JSON

通过访问单个产品页面更新WooCommerce产品元数据

如何实现对数据库表中多列的唯一约束?

在php中,方法之间的属性链接是如何工作的

dyld[45923]:未加载库:/usr/local/opt/libavif/lib/libavif.15dylib

在WooCommercel邮箱通知上添加来自Apaczka插件的选定交付点

PHP 8.2 弃用日志(log)存储在 Laravel 10.22.0 中的哪里?

产品页面自定义复选框可对 WooCommerce 购物车小计启用百分比折扣

如何将子查询结果添加到学说 2 中主查询的末尾?

Symfony 在将它传递给 Twig 时是否从数据库中获取整个对象?

基于其他数组创建多维数组 struct

Laravel 自定义中间件:ERR_TOO_MANY_REDIRECTS