3

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?

2
  • 2
    the pattern needs to be pre and appended with delimiters. You could use a /, like '/\[firstname\]/' Commented Apr 1, 2016 at 13:57
  • Use error reporting in the future. This would have thrown: Delimiter must not be alphanumeric or backslash after the Parse error: syntax error, unexpected ']' on line 12 was fixed. php.net/manual/en/regexp.reference.delimiters.php Commented Apr 1, 2016 at 14:05

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

I feel really stupid in this moment. A quick question: why would you suggest this method over regex (if this can be done with regex too)?
I guess I would go for str_replace because this isn't a complex string replacement where you would benefit from a regular expression match, in fact it's a straight through simple string replace.
Also, it looks like preg_replace is considerably slower than str_replace who'd a thunk it :) here some random benchmark micro-optimization.com/…
3

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

Comments

1

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()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.