douqi3064 2013-05-13 17:09
浏览 22
已采纳

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

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

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

  $regex = [\^[*\]]

thinking this will look for anything inside [] tags

  • 写回答

3条回答 默认 最新

  • duangu4980 2013-05-13 17:27
    关注

    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 >.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用