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.
replace( "[" , "(" ). replace( "]" , ")" );
Brackets can be removed from a string in Javascript by using a regular expression in combination with the . replace() method.
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 ( ).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With