在 PHP 中将“//”替换为“/* */”?
Replace "//" with "/* */" in PHP?
我正在编写代码来缩小 html/css/js 但我遇到了问题。
我需要用 /* 和 */ 替换 //。
示例:
$(funcion(){
// Do something
});
替换为:
$(funcion(){
/* Do something */
});
怎么做?
首先,正如评论中指出的那样,如果您想缩小尺寸,则应删除评论。
function convertComment(str){
if(str.substring(0,2) === '//'){
str = '/*' + str.substring(2) + ' */';
} else {
str = false;
}
return str;
}
您的示例代码看起来像 JQuery,所以如果您正在寻找 PHP,这里是那个版本:
function convertComment($s){
if(substr($s,0,2) == '//'){
$s = '/*' . substr($s,2) . ' */';
} else {
$s = false;
}
return $s;
}
你可以使用这个正则表达式:
/(?m)^\h*\/\/(.*)$/
然后替换为
/**/
替换以 //
开头的每一行或 //
.
之前的任意数量的空格
Regex101 演示:https://regex101.com/r/oE0rY0/1
(?m)
启用 m
修饰符,使 ^
和 $
匹配每一行而不是整个字符串。 \h*
是零个或多个空格。 \/
正在转义第一个 /
,因为它是定界符(可以是任何定界符,然后不需要转义,http://php.net/manual/en/regexp.reference.delimiters.php)。然后 .*
是每个字符,直到行尾 $
。 ()
捕获 //
.
之后找到的值
PHP 用法:
$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, '/**/', $string);
输出:
/*replace me please*/
dont touch http://www.google.com
or //this one
/*but this one do as well*/
PHP 演示:https://ideone.com/j7Xj4L
我正在编写代码来缩小 html/css/js 但我遇到了问题。
我需要用 /* 和 */ 替换 //。
示例:
$(funcion(){
// Do something
});
替换为:
$(funcion(){
/* Do something */
});
怎么做?
首先,正如评论中指出的那样,如果您想缩小尺寸,则应删除评论。
function convertComment(str){
if(str.substring(0,2) === '//'){
str = '/*' + str.substring(2) + ' */';
} else {
str = false;
}
return str;
}
您的示例代码看起来像 JQuery,所以如果您正在寻找 PHP,这里是那个版本:
function convertComment($s){
if(substr($s,0,2) == '//'){
$s = '/*' . substr($s,2) . ' */';
} else {
$s = false;
}
return $s;
}
你可以使用这个正则表达式:
/(?m)^\h*\/\/(.*)$/
然后替换为
/**/
替换以 //
开头的每一行或 //
.
Regex101 演示:https://regex101.com/r/oE0rY0/1
(?m)
启用 m
修饰符,使 ^
和 $
匹配每一行而不是整个字符串。 \h*
是零个或多个空格。 \/
正在转义第一个 /
,因为它是定界符(可以是任何定界符,然后不需要转义,http://php.net/manual/en/regexp.reference.delimiters.php)。然后 .*
是每个字符,直到行尾 $
。 ()
捕获 //
.
PHP 用法:
$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, '/**/', $string);
输出:
/*replace me please*/
dont touch http://www.google.com
or //this one
/*but this one do as well*/
PHP 演示:https://ideone.com/j7Xj4L