简体   繁体   中英

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)

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 мир.! 

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.

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

Here example as your code,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM