Home  >  Article  >  Backend Development  >  How to remove comments in php

How to remove comments in php

王林
王林Original
2021-10-15 16:16:512169browse

php method to remove comments: [function removeComment($content){return preg_replace("/(\/\*(\s|.)*?\*\/)|(\/\/. (\s|.*))|(#(\s*)?(.*))...}].

How to remove comments in php

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

If we want to remove comments in the code, we can use regular expressions to achieve it. Let’s take a look at how to achieve it.

First give a test code:

<?php
 
/**
 * Created by PhpStorm.
 * User: Yang
 * Date: 2019/10/16
 * Time: 10:25
 */
 
// 计算和
// 计算和
// 计算和
$a = 1;
$b = 2;
$c = $a+$b; //总和
 
/*
 * 求和函数
 */
function sum($a, $b) {
 
    return $a + $b; //返回值
}
 
#  第二种注释
$a = 1;
$b = 2;
## 求乘积
$c = $a * $b; #     结果
 
//特殊
$usedFuncs = "abcd";
preg_split("//is", implode("", $usedFuncs), -1, PREG_SPLIT_NO_EMPTY);

Remove the comment code as follows:

/**
 * Created by PhpStorm.
 * User: 25754
 * Date: 2019/10/17
 * Time: 9:54
 */
 
function removeComment($content)
{
    return preg_replace("/(\/\*(\s|.)*?\*\/)|(\/\/.(\s|.*))|(#(\s*)?(.*))/", &#39;&#39;, str_replace(array("\r\n", "\r"), "\n", $content));
}
 
$content = file_get_contents("./test.php");
echo removeComment($content);

Result:

$a = 1;
$b = 2;
$c = $a+$b;
 
function sum($a, $b) {
 
    return $a + $b; }
 
 
$a = 1;
$b = 2;
 
$c = $a * $b;
 
$usedFuncs = "abcd";
preg_split("

Recommended learning: php training

The above is the detailed content of How to remove comments in php. 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