-->

Replace “//” with “/* */” in PHP? [closed]

2019-09-22 05:18发布

问题:

I'm working in a code to minify html/css/js but i got a problem.

I need to replace // with /* and */.

Example:

$(funcion(){
// Do something
});

Replace to:

$(funcion(){
/* Do something */
});

How do that?

回答1:

First, as was pointed out in the comments, if you're looking to reduce the size, comments should be stripped.

function convertComment(str){
   if(str.substring(0,2) === '//'){
       str = '/*' + str.substring(2) + ' */';
   } else {
       str = false;
   }
   return str;
}

Your example code looked like JQuery, so if you were looking for PHP, here is that version:

function convertComment($s){
   if(substr($s,0,2) == '//'){
       $s = '/*' . substr($s,2) . ' */';
   } else {
       $s = false;
   }
   return $s;
}


回答2:

You could use this regex:

/(?m)^\h*\/\/(.*)$/

then replace with

/*$1*/

to replace each line that starts with // or any amount of spaces before the //.

Regex101 Demo: https://regex101.com/r/oE0rY0/1

The (?m) enables the m modifier which makes ^ and $ match each line rather than the whole string. The \h* is zero or more spaces. The \/ is escaping the first / since that is the delimiter (could be any delimiter then wouldn't need to escape, http://php.net/manual/en/regexp.reference.delimiters.php). Then the .* is every character until the end of the line $. The () captures the found value after the //.

PHP Usage:

$string = '//replace me please
dont touch http://www.google.com
or //this one
  //but this one do as well';
$regex = '/^\h*\/\/(.*)$/m';
echo preg_replace($regex, '/*$1*/', $string);

Output:

/*replace me please*/
dont touch http://www.google.com
or //this one
/*but this one do as well*/

PHP Demo: https://ideone.com/j7Xj4L