简体   繁体   中英

Replace all spaces which are enclosed within braces

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.

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

I am reacting to your comment that you dont want to use regex, just string manipulation. That's OK but why have you then written that you are looking for a regex?

Solution wihout regex:

<?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;

?>

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM