Replace all spaces enclosed in braces

What I want to do is find all the spaces enclosed in braces, and then replace them with another character.

Sort of:

{The quick brown} fox jumps {over the lazy} dog

To go to:

{The*quick*brown} fox jumps {over*the*lazy} dog

I’ve already searched on the Internet, but that’s just what I’ve got so far, and it seems so close to what I really want.

preg_replace('/(?<={)[^}]+(?=})/','*',$string);

My problem with the code above is that it replaces everything:

{*} fox jumps {*} dog

I studied regular tutorials to figure out how I should change the code above to just replace spaces, but to no avail. Any input would be appreciated.

Thank.

+5
source share
3 answers

, , lookahead:

$result = preg_replace('/ (?=[^{}]*\})/', '*', $subject);

, :

(?=     # Assert that the following regex can be matched here:
 [^{}]* #  - Any number of characters except braces
 \}     #  - A closing brace
)       # End of lookahead
+5

, , . , , ?

:

<?php

$str = "{The quick brown} fox jumps {over the lazy} dog";

for($i = 0, $b = false, $len = strlen($str); $i < $len; $i++)
{ 
    switch($str[$i])
    {
        case '{': $b = true; continue;
        case '}': $b = false; continue;
        default:
        if($b && $str[$i] == ' ')
            $str[$i] = '*';
    }
}

print $str;

?>
+2

How about this:

$a = '{The quick brown} fox jumps {over the lazy} dog';
$b = preg_replace_callback('/\{[^}]+\}/sim', function($m) {
    return str_replace(' ', '*', $m[0]);
}, $a);
var_dump($b); // output: string(47) "{The*quick*brown} fox jumps {over*the*lazy} dog" 
+1
source

All Articles