【问题标题】:Replace all spaces in string inside curly braces替换花括号内字符串中的所有空格
【发布时间】:2018-12-30 10:56:27
【问题描述】:

我需要替换大括号内字符串中的所有空格(包括前缀)。 示例:

发件人:x{Test test} test test x{Test test test } test {Test test}

x{Test_test} test test x{Test_test_test } test {Test test}

(仅适用于x{} - 当花括号包含 x 前缀时)

我可以在lookhead/lookbehind的帮助下做到这一点,但这在PHP/PCRE中不起作用

`(?<=x\{[^\{\}]+)\s+(?=[^\{\}]+\})`

问题是如何做到 PHP/PCRE 兼容 preg_replace 函数?

【问题讨论】:

  • x{Test_test_test }} 之前的空格怎么办?
  • 跟最后一样:x{ Test test test } => x{ Test_test_test }
  • 使用preg_replace_callback 更容易:preg_replace_callback('~\bx{[^{}]+}~', function ($m) { return preg_replace('~(?&lt;!{)\s++(?!})~', '_', $m[0]); }, $str)

标签: php regex preg-replace pcre


【解决方案1】:

您可以为此使用\G bases 正则表达式:

$str = 'x{Test test} test test x{Test test test } test {Test test}';

$repl = preg_replace('/(?:x{|(?<!^)\G)[^\s}]*\K\s+(?!})/', '_', $str);
//=> x{Test_test} test test x{Test_test_test } test {Test test}

RegEx Demo

正则表达式详细信息:

  • \G 在前一个匹配的末尾或第一个匹配的字符串的开头断言位置。
  • (?:x{|(?&lt;!^)\G):匹配 x{ 或上一场比赛结束
  • \K: 重置当前比赛信息
  • \s+: 匹配 1+ 个空格
  • (?!}):断言我们前面没有}

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 1970-01-01
    • 2015-09-03
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2019-07-31
    • 1970-01-01
    相关资源
    最近更新 更多