Home >Backend Development >PHP Problem >How to delete comments using php regular expressions

How to delete comments using php regular expressions

藏色散人
藏色散人Original
2021-03-10 09:38:282699browse

php regular way to delete comments: first create a PHP sample file a; then create a test file; then use the "highlight_string(removeComment(file_get_contents('./a.php')));" method Just delete the comment.

How to delete comments using php regular expressions

#The operating environment of this article: Windows7 system, PHP7.1, Dell G3 computer.

Regular removal of comments in php code

## Strange needs...

Test code

File: a.php

<?php
/**
 * 加法计算
 * 测试
 */
// 设定$a的值
$a = 10;
// 设定$b的值
$b = 5;
// 加法
$c = $a + $b;
# 输出结果
echo $c;

File: test.php

echo "源码:<br />";
show_source(&#39;./a.php&#39;);
echo "<hr />去除注释后:<br />";
highlight_string(removeComment(file_get_contents(&#39;./a.php&#39;)));/**
 * 去除PHP代码注释
 * @param  string $content 代码内容
 * @return string 去除注释之后的内容
 */function removeComment($content){    
 return preg_replace("/(\/\*.*\*\/)|(#.*?\n)|(\/\/.*?\n)/s", &#39;&#39;, 
 str_replace(array("\r\n", "\r"), "\n", $content));
}

Test output


Execution test.php, the output is as follows:


How to delete comments using php regular expressions

Regular analysis

(\/\*.*\*\/)   匹配 /* */
(#.*?\n)       匹配 #      遇到第一个回车后结束
(\/\/.*?\n)    匹配 //     遇到第一个回车后结束

##[Recommended learning: "PHP Video Tutorial

"】

The above is the detailed content of How to delete comments using php regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn