替换花括号内字符串中的所有空格

Replace all spaces in string inside curly braces

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

发件人: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功能?

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

$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{|(?<!^)\G):匹配 x{ 或上一场比赛结束
  • \K: 重置当前匹配信息
  • \s+: 匹配 1+ 个空格
  • (?!}):断言我们没有 } 紧接前方