【问题标题】:PHP Regex Replace Two Slashes (//) to New LinePHP Regex 将两个斜杠 (//) 替换为新行
【发布时间】:2012-08-29 15:41:42
【问题描述】:

我在这里要做的是获取一个可能包含通常是代码注释的字符串,并将其替换为其他内容,尤其是将其包装在其他内容中。我很确定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); 是我自己能想到的,非常感谢任何帮助!

【问题讨论】:

  • $0 或 \\0 匹配整个事物,$1 是第一个反向引用。

标签: php regex replace comments


【解决方案1】:
preg_replace('~//.*$~m', '', $str);

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

http://ideone.com/Xhmpd

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

这将用foo bar 包裹它们

http://ideone.com/IqkWM

【讨论】:

  • +1 - 虽然自 PHP 4.0.4 起使用 $0 形式作为引用比 \\0 形式更受欢迎。 See the PHP manual.
  • @Richard JP Le Guen:实际上我一直使用$n 形式,不知道现在发生了什么:-S
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多