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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题