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


PHP Regex Replace Two Slashes (//) to New Line

我在这里要做的是获取一个可能具有通常代码注释的字符串,并将其替换为其他内容,尤其是将其包装在其他内容中。我很确定preg_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);

这将删除//行尾之后(包括(的所有内容

http://ideone.com/Xhmpd

preg_replace('~//.*$~m', 'foo ''0 bar', $str);

这将用foo bar包裹它们

http://ideone.com/IqkWM

试试这个:

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