简体   繁体   English

php REGEX帮助替换特定符号内的文本

[英]php REGEX help replace text inside of specific symbols

I have a string with one being 我有一个弦

[my_name] and another being <my_name>

I need to use a regex to search for any text within the [ ] and < > brackets and replace it with BOB 我需要使用正则表达式来搜索[]和<>括号内的任何文本,并将其替换为BOB

I would provide sample code but I don't even know where to begin. 我会提供示例代码,但我什至不知道从哪里开始。 Any help would be appreciated 任何帮助,将不胜感激

So far iv just tried this 到目前为止,iv刚刚尝试过

  $regex = [\^[*\]]

thinking this will look for anything inside [] tags 认为这会在[]标签内寻找任何东西

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 < . $1代表第一个捕获组,可以包含[< The second capturing-group is represented by $2 , which can contain either a ] or a > . 第二个捕获组由$2表示,可以包含]>

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

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

you want to use preg_replace_callback here is a quick example 您想使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM