Replace with same named PHP variable

116 Views Asked by At

My Example:

$name = "Simon";
$string = "My name is [name].";
echo preg_replace("/\[(.*)]/", ${"$1"}, $string);
// Expected: My name is Simon.
// I get: My name is .
// ${"$1"} should be $name?
exit();

When I do only:

echo preg_replace("/\[(.*)]/", "$1", $string);
// I get: My name is name.
// $1 = name

What am i doing wrong? Why is PHP not using the generated $name var? This is only a example. I would like to work this with any replace:

[foo] --> $foo
[bar] --> $bar
...
3

There are 3 best solutions below

20
On BEST ANSWER

As per OP's wish to post my comment as an answer:

In order for this to work, you will need to change [name] to [$name] and ${"$1"} to "$1"

$name = "Simon";
$string = "My name is [$name].";

echo preg_replace("/\[(.*?)]/", "$1", $string);

PHP needs a variable to go on, so using [name] isn't being populated.


As per another and earlier comment I made, alternatively you could very well do:

$name = "Simon";
$string = "My name is " .$name;

echo $string;

If you have a framework with existing brackets, then that is something you haven't told us, only that you said in comments:
" have much more Placeholders, not only [name]", whether it's part of something bigger, then stick to the accepted method.


As per in comments, you could alternatively use "/\[([^\]]+)\]/" instead of "/\[(.*)]/"
Or "/[(.*?)]/" :)

in regards to using for example: "[$foo]bar[$foo]"

7
On

No need in preg_replace at all.
You use variable_names anyway - so php already has this placeholders - "{$var}":

$name = "Simon";
$string = "My name is {$name}.";
1
On

I suggest you to use something like this:

class Tpl {
  private $tpl;
  public function __construct($tpl) {
     $this->tpl = $tpl;
  }
  public function render($data) {
    $result = $this->tpl;
    foreach ($data as $key => $value) {
      $result = str_replace("%%$key%%", str_replace('%%', '', $value), $result);
    }
    return $result;
  }
}

$greet = new Tpl('Hello, %%name%%');
echo $greet->render(array('name' => 'World'));

But you always must care, that you correctly escape your placeholder formatting. I just remove it :)