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);
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36a35-2c027.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36a35-2c027.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?