[英]Replace all spaces in string inside curly braces
I need to replace all spaces in strings inside curly braces (including a prefix). 我需要替换花括号(包括前缀)中的字符串中的所有空格。 Example:
例:
From: x{Test test} test test x{Test test test } test {Test test}
来自:
x{Test test} test test x{Test test test } test {Test test}
To x{Test_test} test test x{Test_test_test } test {Test test}
进行
x{Test_test} test test x{Test_test_test } test {Test test}
(only applies to x{}
- when curly braces include x prefix) (仅适用于
x{}
-大括号包含x前缀时)
I can do it with help of lookhead/lookbehind but this does not work in PHP/PCRE 我可以在lookhead / lookbehind的帮助下完成此操作,但这在PHP / PCRE中不起作用
`(?<=x\{[^\{\}]+)\s+(?=[^\{\}]+\})`
The problem is how to do it PHP/PCRE compatible with preg_replace function? 问题是如何使PHP / PCRE与preg_replace函数兼容?
You may use \\G
bases regex for this: 您可以为此使用
\\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 Details: 正则表达式详细信息:
\\G
asserts position at the end of the previous match or the start of the string for the first match. \\G
在上一场比赛的末尾或首场比赛的字符串开头声明位置。 (?:x{|(?<!^)\\G)
: Matches x{
or end of previous match (?:x{|(?<!^)\\G)
:匹配x{
或上一个匹配的结尾 \\K
: Reset current match info \\K
:重置当前比赛信息 \\s+
: Match 1+ whitespace \\s+
:匹配1+空白 (?!})
: Assert we don't have an }
immediate ahead (?!})
:声明我们前面没有}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.