5

我想要做的是找到用大括号括起来的所有空格,然后用另一个字符替换它们。

就像是:

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

更改为:

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

我已经在网上搜索过,但到目前为止我得到的只有这个,而且它似乎非常接近我真正想要的。

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

我对上述代码的问题是它替换了所有内容:

{*} fox jumps {*} dog

我正在研究正则表达式教程,以弄清楚我应该如何修改上面的代码以仅替换空格但无济于事。任何输入将不胜感激。

谢谢。

4

3 回答 3

5

假设所有大括号都正确嵌套,并且没有嵌套大括号,您可以使用前瞻断言来执行此操作:

$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
于 2012-10-02T06:57:17.807 回答
2

我正在对您的评论做出反应,即您不想使用正则表达式,只是字符串操作。没关系,但你为什么还要写你正在寻找一个正则表达式?

没有正则表达式的解决方案:

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

?>
于 2012-10-02T07:34:45.233 回答
1

这个怎么样:

$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" 
于 2012-10-02T06:57:25.667 回答