Search code examples
phpregexpreg-replacepcre

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}

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

(only applies to x{} - when curly braces include x prefix)

I can do it with help of lookhead/lookbehind but this does not work in PHP/PCRE

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

The problem is how to do it PHP/PCRE compatible with preg_replace function?


Solution

  • You may use \G bases regex for this:

    $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

    RegEx Details:

    • \G asserts position at the end of the previous match or the start of the string for the first match.
    • (?:x{|(?<!^)\G): Matches x{ or end of previous match
    • \K: Reset current match info
    • \s+: Match 1+ whitespace
    • (?!}): Assert we don't have an } immediate ahead