如何使用php从文件/字符串的开头删除注释
我有几个文本文件,包括在我的代码编程。我需要一个正则表达式,以便能够捕获并从捕获的字符串中删除注释的内容。(评论中包含) 捕获文件内容的代码是:如何使用php从文件/字符串的开头删除注释,php,regex,Php,Regex,我有几个文本文件,包括在我的代码编程。我需要一个正则表达式,以便能够捕获并从捕获的字符串中删除注释的内容。(评论中包含) 捕获文件内容的代码是: ob_start(); include($file); $c = ob_get_contents(); ob_end_clean(); $file的示例内容如下所示: //Comment here //Second line //All the comment lines are optional <p>Html content here
ob_start();
include($file);
$c = ob_get_contents();
ob_end_clean();
$file的示例内容如下所示:
//Comment here
//Second line
//All the comment lines are optional
<p>Html content here</p>
<?php echo "Php content may also exists!"; ?>
//在这里注释
//第二线
//所有注释行都是可选的
这里的Html内容
欢迎提供任何帮助。解决此问题的一种方法是使用带有多行标志/修饰符的正则表达式,该标志/修饰符将匹配以/
开头的所有行
见:
$re='~^\s*/.$\s*~m';
$str=“//此处注释\n//第二行\n//所有注释行都是可选的\n此处的Html内容\n”;
echo preg_替换($re,“,$str);
正则表达式细分:
-行的开头(我们使用的是^
修饰符)/m
-可选空白(出现0次或更多)\s*
-两个正斜杠/
-除换行符以外的任何零个或多个字符*
-行尾(我们使用的是$
修饰符)/m
-可选空白(用于修剪换行符)\s*
/
开头的所有行
见:
$re='~^\s*/.$\s*~m';
$str=“//此处注释\n//第二行\n//所有注释行都是可选的\n此处的Html内容\n”;
echo preg_替换($re,“,$str);
正则表达式细分:
-行的开头(我们使用的是^
修饰符)/m
-可选空白(出现0次或更多)\s*
-两个正斜杠/
-除换行符以外的任何零个或多个字符*
-行尾(我们使用的是$
修饰符)/m
-可选空白(用于修剪换行符)\s*
$c=“//此处注释\n//第二行\n//所有注释行都是可选的\n此处的Html内容\n”;
$output=“”;
$stripComments=true;
foreach(preg_split(“/(\r?\n)|(\r\n?)/”,$c)作为$line){
如果($注释){
如果(预匹配(“~^\s*/~”,$line))
继续;
否则{
$stripComments=false;
$output.=$line.“\n”;
}
}
其他的
$output.=$line.“\n”;
}
回显“$output”;
如果您只想在实际代码开始之前删除注释,则需要一个状态机(regex解决方案更紧凑,但在任何地方删除行注释):
$c=“//此处注释\n//第二行\n//所有注释行都是可选的\n此处的Html内容\n”;
$output=“”;
$stripComments=true;
foreach(preg_split(“/(\r?\n)|(\r\n?)/”,$c)作为$line){
如果($注释){
如果(预匹配(“~^\s*/~”,$line))
继续;
否则{
$stripComments=false;
$output.=$line.“\n”;
}
}
其他的
$output.=$line.“\n”;
}
回显“$output”;
也许,//第四条注释
?是的,php代码中可能也有注释,但只应删除划线开头的注释。您如何更改$file以使用有效的php注释?例如,
不幸的是,我无法改变这一点,文件的格式是givenWell,也许,使用正则表达式会更容易。试试看。也许,//第四条注释
?是的,php代码中可能也有注释,但只应删除划线开头的注释。将$file更改为使用有效的php注释怎么样?例如,
不幸的是,我无法改变这一点,文件的格式是givenWell,也许,使用正则表达式会更容易。试试看,谢谢!还有,你所说的“不大”是指多少kb?实际上,我不知道,因为我主要用C语言编写代码。在C#中,我遇到了超过30MB字符串的内存问题。哦,我没有这么大的文件。我想我不会有超过500kb的文件。再次感谢,谢谢!还有,你所说的“不大”是指多少kb?实际上,我不知道,因为我主要用C语言编写代码。在C#中,我遇到了超过30MB字符串的内存问题。哦,我没有这么大的文件。我想我不会有超过500kb的文件。再次感谢。@Stribizov已经给了我有效的答案,但我也非常感谢你的回答。谢谢您的时间。@Zoli:谢谢您的欣赏,如果您知道注释仅在正则表达式解决方案的代码之上,那么就可以了ok@stribizhev已经给了我有效的答案,但我也非常感谢你的回答。谢谢您的时间。@Zoli:谢谢您的欣赏,如果您知道注释仅在代码上方,则正则表达式解决方案是可以的
$re = '~^\s*//.*$\s*~m';
$str = "//Comment here\n//Second line\n//All the comment lines are optional\n<p>Html content here</p>\n<?php echo \"Php content may also exists!\"; ?>";
echo preg_replace($re, "", $str);
$c = "//Comment here\n//Second line\n//All the comment lines are optional\n<p>Html content here</p>\n<?php echo \"Php content may also exists!\"; ?>";
$output = "";
$stripComments = true;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $c) as $line) {
if ( $stripComments ) {
if ( preg_match("~^\s*//~",$line) )
continue;
else {
$stripComments = false;
$output .= $line."\n";
}
}
else
$output .= $line."\n";
}
echo "$output";