简体   繁体   English

替换括号内的所有空格

[英]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" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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