PHP正则表达式将两个斜杠(//)替换为新行

PHP正则表达式将两个斜杠(//)替换为新行,php,regex,replace,comments,Php,Regex,Replace,Comments,我在这里要做的是获取一个字符串,该字符串可能包含通常的代码注释,并用其他内容替换它,特别是用其他内容包装它。我很确定preg\u replace函数在这里可以工作,但我不知道从哪里开始使用正则表达式。例如: Hello world //this is a comment Testing //not testing Test again 会变成 Hello world %//this is a comment% Testing %//not testing% Test again preg_r

我在这里要做的是获取一个字符串,该字符串可能包含通常的代码注释,并用其他内容替换它,特别是用其他内容包装它。我很确定
preg\u replace
函数在这里可以工作,但我不知道从哪里开始使用正则表达式。例如:

Hello world //this is a comment
Testing //not testing
Test again
会变成

Hello world %//this is a comment%
Testing %//not testing%
Test again
preg_replace(“???”、“%$1%”、$matches)
是我自己能想到的,非常感谢您的帮助

preg_replace('~//.*$~m', '', $str);
这将删除(包括)
/
到行尾的所有内容

这将用
foo-bar
环绕它们

试试这个:

$string = "Hello world //this is a comment";
preg_replace('/\/\/.*/', '%$0%', $string);

$0或\\0与整个内容匹配,$1是第一个反向引用。+1-尽管由于PHP 4.0.4使用
$0
格式作为引用比
\\0
格式更可取@Richard JP Le Guen:实际上我一直使用
$n
表单,不确定现在发生了什么:-S
$string = "Hello world //this is a comment";
preg_replace('/\/\/.*/', '%$0%', $string);