1

我正在尝试将某个字符串中所有出现的“ a ”替换为“ b ”。问题是我只需要替换括号内的那些字母:

asd asd asd [asd asd asd] asd asd asd

现在我有这个代码:

$what = '/(?<=\[)a(?=.*?\])/s';
$with = 'b';
$where = 'asd asd asd [asd asd asd] asd asd asd';

但它只替换了第一个“a”,我得到了这个结果:

asd asd asd [bsd asd asd] asd asd asd

我真的只需要一个 preg_replace 调用就可以做到这一点。

4

2 回答 2

3

试试这个(这正是乔恩解释的)

function replace_a_with_b($matches)
{
  return str_replace("a", "b", $matches[0]);
}
$text = 'asd asd asd [asd asd asd] asd asd asd';
echo preg_replace_callback("#(\[[^]]+\])#", "replace_a_with_b", $text);

输出:

asd asd asd [bsd bsd bsd] asd asd asd
于 2013-08-26T13:34:05.107 回答
2

您不能通过单个preg_replace调用来执行此操作,因为后视需要说“在匹配之前的某处有一个左方括号”,这是不可能的,因为后视模式必须具有固定长度。

为什么你绝对需要在一个电话中做到这一点?使用 非常容易实现preg_replace_callback,您可以在其中匹配方括号内的内容组并preg_replace每次都在匹配项上使用(或者str_replace如果您要做的只是将“a”替换为“b”,则只是一个简单的)。

例子:

$what = '/\[([^]]*)\]/';
$where = 'asd asd asd [asd asd asd] asd asd asd';

echo preg_replace_callback(
    $what, 
    function($match) {
        return '['.str_replace('a', 'b', $match[1]).']';
    },
    $where);
于 2013-08-26T13:31:41.027 回答