Home >Backend Development >PHP Tutorial >Use regular expressions to remove comment methods in php code_php example
Regular expression is a grammatical rule that describes a string result. It is a specific formatting pattern that can match, replace, and intercept matching strings. Commonly used languages basically have regular expressions, such as JavaScript, java, etc. In fact, as long as you understand the regular use of one language, it is relatively simple to use the regular rules of other languages. This article mainly introduces a method of using regular rules to remove comments in php code
test code
file: a.PHP
<?php /** * 加法计算 * 测试 */ // 设定$a的值 $a = 10; // 设定$b的值 $b = 5; // 加法 $c = $a + $b; # 输出结果 echo $c;
File: test.php
echo "源码:<br />"; show_source('./a.php'); echo "<hr />去除注释后:<br />"; highlight_string(removeComment(file_get_contents('./a.php'))); /** * 去除PHP代码注释 * @param string $content 代码内容 * @return string 去除注释之后的内容 */ function removeComment($content){ return preg_replace("/(\/\*.*\*\/)|(#.*?\n)|(\/\/.*?\n)/s", '', str_replace(array("\r\n", "\r"), "\n", $content)); }
Test output
Execute test .php, the output is as follows:
Regular Analysis
(\/\*.*\*\/) 匹配 /* */ (#.*?\n) 匹配 # 遇到第一个回车后结束 (\/\/.*?\n) 匹配 // 遇到第一个回车后结束
The above is the detailed content of Use regular expressions to remove comment methods in php code_php example. For more information, please follow other related articles on the PHP Chinese website!