Oleksii
Oleksii

Reputation: 59

Replace {{word}} in string

Have a string: $str = "Hello, {{first_name}} {{last_name}}!";

And variables $first, $last... in array

$trans = array("{{first_name}}" => $first, "{{last_name}}" => $last, "{{cart}}" => $crt1, "{{phone}}" => $phone, "{{adds}}" => $addr, "{{order_id}}" => $order_id);

How to replace {{first_name}}->$first, {{last_name}}->$last

Here what i did:

function replace_str($str, $trans)
{
    $subj = strtr($str, $trans);
    return $subj;
}

$cart = replace_str($str,$trans);

But strtr doesn't work with cyrillic (utf-8)

Upvotes: 0

Views: 121

Answers (4)

Ketan Yekale
Ketan Yekale

Reputation: 2223

You can use str_replace with array_keys.

PHP Code:

<?php
$str = "Hello, {{first_name}} {{last_name}}!";
$first = "ХѠЦЧШЩЪЪІ";
$last = "ЬѢꙖѤЮѪ";
$crt1 = "";
$phone = "";
$addr = "";
$order_id = "";
$trans = array("{{first_name}}" => $first, "{{last_name}}" => $last, "{{cart}}" => $crt1, "{{phone}}" => $phone, "{{adds}}" => $addr, "{{order_id}}" => $order_id);

echo str_replace(array_keys($trans), array_values($trans), $str);

Check the output at: https://3v4l.org/0fCv3

Refer:

  1. http://php.net/manual/en/function.str-replace.php

  2. http://php.net/manual/en/function.array-keys.php

Upvotes: 0

Jaydeep Mor
Jaydeep Mor

Reputation: 1703

You can use str_replace() or str_ireplace() for case insensitive version.

Here example as your code,

str_replace(array_keys($trans), $trans, $str);

Upvotes: 0

steffen
steffen

Reputation: 16948

Your code is fine. strtr() supports multibyte strings, but the array form strtr(string, array) should be used. Example:

$str = "Hello {{first_name}}!";
$first_name = "мир.";
$trans = ['{{first_name}}' => $first_name];
echo strtr($str, $trans); // Hello мир.! 

Upvotes: 1

LahiruTM
LahiruTM

Reputation: 648

use str_replace(); , you can resolve your problem.

$str = "Hello, {{first_name}} {{last_name}}!";
$str1 = str_replace("{{first_name}}",$first,$str);
$str2 = str_replace("{{last_name}}",$last,$str1);
echo $str2;

First i have replaced {{first_name}} with $first in $str. Then I have replaces {{last_name}} with $last in $str1.

Upvotes: 0

Related Questions