Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php preg_replace()所有发生的事件_Php_Regex_Preg Replace - Fatal编程技术网

Php preg_replace()所有发生的事件

Php preg_replace()所有发生的事件,php,regex,preg-replace,Php,Regex,Preg Replace,我想创建一个脚本,删除文件中的所有注释。我现在的正则表达式是: $new = preg_replace_all("/(\/\*.*\*\/)/s", "", $contents); 它匹配(并删除)介于/*和*/ 当文件的内容如下所示时,问题就变得很明显,例如: /* First comment */ first_function(); /* Second comment */ second_function(); 我的正则表达式没有删除第一个和第二个注释并保留两个函数调用,而是匹配从

我想创建一个脚本,删除文件中的所有注释。我现在的正则表达式是:

$new = preg_replace_all("/(\/\*.*\*\/)/s", "", $contents);
它匹配(并删除)介于
/*
*/

当文件的内容如下所示时,问题就变得很明显,例如:

/* First comment */ 
first_function();

/* Second comment */ 
second_function();
我的正则表达式没有删除第一个和第二个注释并保留两个函数调用,而是匹配从第一个
/*
到最后一个
*/
的所有内容,从而完全删除
第一个函数()

我想一个解决方案是用匹配任何内容的内容替换我的
*
(匹配任何内容),直到你到达
*/
。但我不知道怎么写。我希望它是类似于
[^\*\/]
的东西,但它没有按预期工作


什么是正确的正则表达式

你们非常接近。您只需在
*
之后使用非贪婪匹配字符
,如下所示:

$new = preg_replace_all("/(\/\*.*?\*\/)/s", "", $contents);
                                 ^
                                 ^
                                 ^
                                 ^
你只需要一个问号


在工作中看到这个

非贪婪匹配字符。。。我喜欢它的名字:P谢谢。