wiredmark
wiredmark

Reputation: 1108

PHP Regex replace text between brackets AND brackets

I have the following string:

Welcome [firstname] [lastname]

I am trying to use preg_replace() so that [firstname] is replaced with Marcello and [lastname] with Silvestri.

I have only been able to find the way to get the text inside the brackets, but I want to replace the brackets themselves.

$string = "Welcome [firstname] [lastname]";

$patterns = array();
$patterns[0] = '\[firstname\]';
$patterns[1] = '\[lastname\]';

$replacements = array();
$replacements[0] = 'Marcello';
$replacements[1] = 'Silvestri';

echo preg_replace($patterns, $array, $string]);

I also tried with \[(.*?)\] trying to replace everything regardless of the square brackets content, but I get something like [Marcello], while I just want Marcello.

How can I replace the content including the square brackets?

Upvotes: 3

Views: 3754

Answers (3)

Mardin101
Mardin101

Reputation: 73

You can achieve this with str_replace(). Did a small test, you can see the code below:

$string = "Welcome [firstname] [lastname]";
$patterns = array("Marcello", "Silvestri");
$replace = array("[firstname]", "[lastname]");

$result = str_replace($replace, $patterns , $string);

echo $result;

see also PHP str_replace()

Upvotes: 1

Below is your pattern. using @solves your problem. and check it in sandbox here

 $string = "Welcome [firstname] [lastname]";

$patterns = array();
$patterns[0] = '@\[firstname\]@';//this is what you need
$patterns[1] = '@\[lastname\]@';

$replacements = array();
$replacements[0] = 'Marcello';
$replacements[1] = 'Silvestri';

echo preg_replace($patterns, $replacements, $string);

Upvotes: 3

Alex Andrei
Alex Andrei

Reputation: 7283

You don't really need regex for this, so here's a simple str_replace example.

$string = "Welcome [firstname] [lastname]";

$find = [
    '[firstname]','[lastname]'
];
$replace = [
    'Marcellus','Wallace'
];

$modified = str_replace($find,$replace,$string);

print $modified;

Will output

Welcome Marcellus Wallace

Upvotes: 5

Related Questions