Search code examples
phpregexarrayscurly-brackets

PHP: Replace certain parts of string with array values


I want to replace values in a string if a particular string exists in an array.

$str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';

$array = array(
    'name' => '010 Pixel',
    'city' => 'USA',
    'hobby' => 'code',
    'email' => 'xyz@abc.com'
);

I want to replace {{name}} with the value of name in $array. If the string inside curly brackets doesn't exist in the $array then let that string stay as it is.

Expected result:

My name is 010 Pixel. I live in USA. I love to code. {{ops...}}

The reason I'm concern about this is, when any value coming from form contains any {{field-name}} then it shouldn't get replaced. I want to replace only what is set in $str.


Solution

  • There is strtr function.

    $str = 'My name is {{name}}. I live in {{city}}. I love to {{hobby}}. {{ops...}}';
    
    $array = array(
        '{{name}}' => '010 Pixel',
        '{{city}}' => 'USA',
        '{{hobby}}' => 'code',
        '{{email}}' => 'xyz@abc.com'
    );
    echo strtr($str, $array);