我有一个字符串,其中一个是
[my_name] and another being <my_name>
我需要使用正则表达式来搜索[]和<并将其替换为BOB
>并将其替换为CC_1>
我会提供示例代码,但我甚至不知道从哪里开始。如有任何帮助,不胜感激
到目前为止,我只是尝试了这个
$regex = ['^[*']]
认为这将查找[]标签内的任何内容
我想下面的代码应该可以工作:
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
表示,它可以包含]
或>
。
$str = "[my_name] and another being <my_name>";
$replace = "BOB";
preg_replace('/(['[<])[^']]*([']>])/i', "$1".$replace."$2", $str);
你想使用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);