替换用方括号或尖括号括起来的字符串中的占位符

问题描述 投票:0回答:4

我有一根绳子,上面有一个存在

[my_name] and another being <my_name>

我需要使用正则表达式来搜索 [ ] 和 < > 括号内的任何文本,并将其替换为

BOB

到目前为止我刚刚尝试过这个:

$regex = [\^[*\]]

...认为这会查找 [] 标签内的任何内容。

php regex replace placeholder brackets
4个回答
1
投票

我想以下应该有效:

preg_replace('/([\[<])[^\]>]+([\]>])/', "$1BOB$2", $str);

正则表达式的解释:

([\[<]) -> First capturing group. Here we describe the starting characters using
           a character class that contains [ and < (the [ is escaped as \[)
[^\]>]+ -> The stuff that comes between the [ and ] or the < and >. This is a
           character class that says we want any character other than a ] or >.
           The ] is escaped as \].
([\]>]) -> The second capturing group. We we describe the ending characters using
           another character class. This is similar to the first capturing group.

替换模式使用反向引用来引用捕获组。

$1
代表第一个捕获组,可以包含
[
<
。第二个捕获组由
$2
表示,它可以包含
]
>


1
投票
$str = "[my_name] and another being <my_name>";
$replace = "BOB";

preg_replace('/([\[<])[^\]]*([\]>])/i', "$1".$replace."$2", $str);

1
投票

你想使用

preg_replace_callback
这是一个简单的例子

$template = "Hello [your_name], from [my_name]";
$data = array(
    "your_name"=>"Yevo",
    "my_name"=>"Orangepill"
);

$func = function($matches) use ($data) {
    print_r($matches);
    return $data[$matches[1]];
};

echo preg_replace_callback('/[\[|<](.*)[\]\)]/U', $func, $template);

0
投票

前面所有答案都缺失的一个区别是,您需要限定具有匹配大括号的占位符。 他们的片段将全部替换不匹配的大括号。 只需在两个表达式之间使用交替 (

|
) 即可。

代码:(演示

$text = <<<TEXT
This is [my_name] and another being <my_name> but this isn't <my_name] because the braces don't match!
TEXT;

$replacement = 'BOB';

echo preg_replace('/\[\w+]|<\w+>/', $replacement, $text);

输出:

This is BOB and another being BOB but this isn't <my_name] because the braces don't match!
© www.soinside.com 2019 - 2024. All rights reserved.