There are multiple values in the array, but only a few of them need to be matched and replaced. How to write more efficiently?

$arr = array(
  "a" => "1"
  "b" => "2"
  "c" => "3"
  "d" => "4"
  "e" => "5"
  "f" => "6"
);

$str = array(
    "xxxxx{a}xxxxx{b}xxxx{f}xxxx",
    "xxxxx{b}xxxxx{c}xxxx{d}xxxx",
    "xxxxx{a}xxxxx{d}xxxx{e}xxxx",
);

the way I came up with is


foreach($str as $v)
{
    foreach($arr as $ke=>$va)
    {
        $v = str_replace("{".$ke."}", $va, $v);
    }
    $newStr[] = $v;
}
return $newStr;

it doesn"t feel good to go through all the $arr every time.

can you guys give me some advice?

Mar.04,2021

read more documents
str_replace

clipboard.png


array_walk($str, function(&$v, $k) use ($arr){
    $v = strtr($v, $arr);
});

if you don't want to loop, you can try this:

$arr = array(
  '{a}' => '1',
  '{b}' => "2",
  '{c}' => "3",
  '{d}' => "4",
  '{e}' => "5",
  '{f}' => "6",
);

$str = array(
    'xxxxx{a}xxxxx{b}xxxx{f}xxxx',
    'xxxxx{b}xxxxx{c}xxxx{d}xxxx',
    'xxxxx{a}xxxxx{d}xxxx{e}xxxx',
);

$newStr = implode('|||', $str);
$newStr = strtr($newStr, $arr);
$newStr = explode('|||', $newStr);
print_r($newStr);

another tips: pure string using single quotation marks is a little bit faster than double quotation marks


I don't know if this is the result you want.

$result = array_map(function($item) use ($arr) {
    return str_replace(array_keys($arr), array_values($arr), $item);
}, $str);
Menu