繁体   English   中英

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

[英]PHP Regex Replace Two Slashes (//) to New Line

我在这里尝试做的是获取一个字符串,该字符串可能具有通常的代码注释,并将其替换为其他内容,尤其是将其包含在其他内容中。 我很确定preg_replace函数可以在这里工作,但我不知道从哪里开始使用Regex。 例如:

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM