Replace all spaces which are enclosed within braces
php, preg-match, preg-replace, regex
Solution
Assuming that all braces are correctly nested, and that there are no nested braces, you can do this using a lookahead assertion:
$result = preg_replace('/ (?=[^{}]*\})/', '*', $subject);
This matches and replaces a space only if the next brace is a closing brace:
(?= # Assert that the following regex can be matched here:
[^{}]* # - Any number of characters except braces
\} # - A closing brace
) # End of lookahead
Problem
What I want to do is find all spaces that are enclosed in braces, and then replace them with another character. Something like: ``` {The quick brown} fox jumps {over the lazy} dog ``` To change into: ``` {The*quick*brown} fox jumps {over*the*lazy} dog ``` I already searched online, but only this is what I got so far, and it seems so close to what I really want. ``` preg_replace('/(?<={)[^}]+(?=})/','*',$string); ``` My problem with the above code is that it replaces everything: ``` {*} fox jumps {*} dog ``` I was looking into regexp tutorials to figure out how i should modify the above code to only replace spaces but to no avail. Any input will be highly appreciated. Thanks.