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

How to remove comments in php using regular expressions

王林
Release: 2023-03-06 06:34:02
Original
2313 people have browsed it

php uses regular expressions to remove comments: ["/(\/\*.*\*\/)|(#.*?\n)|(\/\/.*?\n) /s"]. [(\/\/.*?\n)] means matching [//] and ends after encountering the first carriage return.

How to remove comments in php using regular expressions

Specific method:

(Recommended tutorial: php video tutorial)

File: a .PHP

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

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));
}
Copy after login

Test output:

Execute test.php, the output is as follows:

How to remove comments in php using regular expressions

Regular analysis:

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

Related recommendations: php training

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

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template