替换变量中可能的常量


Replacing possible constants in a variable

我设置了大量常量。我从数据库中得到了一些短语,这些短语中可能有这些常量名称。

我想用常量的值替换它们的名称。

Constants:
Array
(
[WORK1] => Pizza Delivery
[WORK2] => Chauffer
[WORK3] => Package Delivery
)

变量:

$variable[0] = "I like doing WORK1";
$variable[1] = "Nothing here move along";
$variable[2] = "WORK3 has still not shown up.";

我该如何得到那些具有正确常数值的变量?常量的顺序可以是未排序的,也可以是变量。

应该像一样简单

foreach ($variable as &$v)
{
  $v = str_replace(array_keys($constants), array_values($constants), $v);
}
unset($v);

请注意,在循环之前这样做可能更为优化:

$keys = array_keys($constants);
$vals = array_values($constants);

然后直接使用它们,而不是在每次迭代中调用array_key/vals。

仔细想想,这可能是最好的:

foreach ($variable as &$v)
{
  $v = strtr($v, $constants);
}
unset($v);

因为它不是从前到后处理的,而且无论常量如何排序,都应该获得一致的行为。