Search code examples
phpregexvariablespreg-replacepreg-replace-callback

Replace with same named PHP variable


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

Solution

  • 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]"