Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 906
Bibokid Avatar asked Oct 02 '12 06:10

Bibokid


People also ask

How do you replace square brackets with spaces in Java?

replace( "[" , "(" ). replace( "]" , ")" );

How do you remove a string from a bracket?

Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.

How do you change curly brackets in Java?

Summary. If one needs to use the replace() function to replace any open curly brackets "{" contained within a String with another character, you need to first escape with a backslash "\". This syntax not only applies to curly brackets { }, but also with "square brackets" [ ] and parentheses ( ).


3 Answers

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
like image 77
Tim Pietzcker Avatar answered Oct 08 '22 08:10

Tim Pietzcker


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;

?>
like image 42
Zaffy Avatar answered Oct 08 '22 06:10

Zaffy


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" 
like image 1
Zathrus Writer Avatar answered Oct 08 '22 06:10

Zathrus Writer