簡體   English   中英

替換變量中可能的常量

[英]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);

因為它不會從頭到尾處理,並且無論常量如何排序,都應該獲得一致的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM