替换变量中可能的常量

发布于 2024-11-17 07:49:30 字数 402 浏览 1 评论 0原文

我设置了很多常量。 我有来自数据库的短语,其中可能包含这些常量名称。

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

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.";

我如何获得那些具有正确常量值的变量?常量和变量的顺序可以是未排序的。

I have loads of constants set.
I have phrases from database that might have those constant names in them.

I want to replace the constants names with their values.

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

Variables:

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

How would I get those variables with the right constant vales on them? Constants order could be unsorted as well as variables.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹雪碎 2024-11-24 07:49:30

应该简单如下:

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);

因为它不会从头到尾处理,并且无论常量如何排序,您都应该获得一致的行为。

Should be as simple as:

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

Note that it is probably more optimal to do something like this before the loop:

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

And then use them directly instead of calling array_key/vals during every iteration.

And on second thought, this is probably best:

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

because it doesn't process first to last, and you should get consistent behavior regardless of how the constants are sorted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文