我有一个字符串
[my_name] and another being <my_name>
我需要使用正则表达式来搜索 [ ] 和 < > 括号内的任何文本并将其替换为BOB
我会提供示例代码,但我什至不知道从哪里开始。任何帮助,将不胜感激
到目前为止 iv 刚刚尝试过这个
$regex = [\^[*\]]
认为这将在 [] 标签中查找任何内容
你想在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);
I imagine that the following should work:
preg_replace('/([\[<])[^\]>]+([\]>])/', "$1BOB$2", $str);
Explanation of the regex:
([\[<]) -> 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.
The replacement pattern uses backreferences to refer to the capturing groups. $1
stands for the first capturing-group which can contain either a [
or a <
. The second capturing-group is represented by $2
, which can contain either a ]
or a >
.
$str = "[my_name] and another being <my_name>";
$replace = "BOB";
preg_replace('/([\[<])[^\]]*([\]>])/i', "$1".$replace."$2", $str);