phpregexreplaceplaceholderbrackets

Replace placeholder in a string which are wrapped in square brackets or angle brackets


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

So far I've just tried this:

$regex = [\^[*\]]

...thinking this will look for anything inside [] tags.


Solution

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