0
$str = "Hello {{name}} welcome to {{company_name}}";

$array = ['name' => 'max', 'company_name' => 'Stack Exchange'];

how to replace {{name}} and {{company_name}} using array value. any php function that return output like

Hello max welcome to Stack Exchange
3
  • it's work for preg_replace_callback Commented Jun 14, 2016 at 15:30
  • thanks for your reply can you give me example Commented Jun 14, 2016 at 15:32
  • If your goal was printing rather than getting a string, try echo 'Hello'.$name.', Welcome to '.$company; Commented Jun 14, 2016 at 15:39

2 Answers 2

1

First create a new array with your search fields, wrapped in curly braces:

$searchArray = array_map(function($value) {
    return "{{" . $value . "}}";
}, array_keys($array));

Now you have an array with the tokens you are searching for, and you already have an array of values you want to replace the tokens with.

So just do a simple str_replace:

echo str_replace($searchArray, $array, $str);

Working example: https://3v4l.org/8tPZt


Here's a tidy little function put together:

function fillTemplate($templateString, array $searchReplaceArray) {
    return str_replace(
        array_map(function($value) { return "{{" . $value . "}}"; }, array_keys($searchReplaceArray)),
        $searchReplaceArray,
        $templateString
    );
}

Now you can call it like this:

echo fillTemplate(
    "Hello {{name}} welcome to {{company_name}}",
    ['name' => 'max', 'company_name' => 'Stack Exchange']
);

// Hello max welcome to Stack Exchange

Example: https://3v4l.org/rh0KX

Sign up to request clarification or add additional context in comments.

Comments

0

Checkout this nice function of PHP: http://php.net/manual/de/function.strtr.php You can find there examples and explanation of it.

$str = "Hello {{name}} welcome to {{company_name}}";

$array = ['{{name}}' => 'max', '{{company_name}}' => 'Stack Exchange'];

print strtr ($str, $array);

9 Comments

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.
OK, then...i change it
Nice edit, but you don't explain it.
English is not my bith language, but i still try to help. And i personally would prefer Link. If that against the concept of Stack Overflow. Sry. For me is SO instant help on instant qeustions. I agree some explanations should way more detailed, but not on this question here ;)
Because I am not going to add yet another answer to a duplicate question. ¯\_(ツ)_/¯ I have dozens of copy 'n paste comments because so many do the same exact thing over and over again.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.