Yeak
Yeak

Reputation: 2538

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.

Upvotes: 0

Views: 130

Answers (4)

mickmackusa
mickmackusa

Reputation: 47991

A distinction that all of the previous answers are missing is that you need to qualify placeholder which have matching braces. Their snippets will all replace mismatched braces. Just use alternation (|) between the two expressions.

Code: (Demo)

$text = <<<TEXT
This is [my_name] and another being <my_name> but this isn't <my_name] because the braces don't match!
TEXT;

$replacement = 'BOB';

echo preg_replace('/\[\w+]|<\w+>/', $replacement, $text);

Output:

This is BOB and another being BOB but this isn't <my_name] because the braces don't match!

Upvotes: 0

Orangepill
Orangepill

Reputation: 24655

you want to use preg_replace_callback here is a quick example

$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);

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95568

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

Upvotes: 1

Desolator
Desolator

Reputation: 22759

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

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

Upvotes: 1

Related Questions