数组合并:保留文字变量

时间:2014-10-15 09:01:19

标签: php arrays laravel laravel-4

让我直接跳到我的问题中。

构建

我有一些简单的语言文件只返回一个包含语言字符串的关联数组(如果有任何帮助的话,这就是Laravel)。不要担心变量,这仅仅是出于示范目的。

郎/ EN /的common.php

<?php return [
"yes"=>"Yes",
"no"=>"No",
"hello"=>"Hello {$name}!",
"newstring"=>"This string does not exist in the other language file",
"random_number"=>"Random number: ".rand(1,10)
];

郎/ DA /的common.php

<?php return [
"yes"=>"Ja",
"no"=>"Nej",
"hello"=>"Hej {$name}!"
];

现在,正如您所看到的,索引newstring并不存在于丹麦语言文件中。我写了一个脚本,而不是必须记住添加所有索引的所有语言文件而不是一个,这基本上是这样做的:

$base_lang = require('lang/en/common.php');
$language_to_merge = require('lang/da/common.php');
$merged_lang = array_replace_recursive($base_lang, $language_to_merge);
file_put_contents('lang/da/common.php', var_export($merged_lang, true));

问题

到目前为止,这么好。现在,我们说$name = "John Doe";。根据PHP的本质,运行此脚本后,lang/da/common.php现在将是

<?php return [
    "yes"=>"Ja",
    "no"=>"Nej",
    "hello"=>"Hej John Doe!",
    "newstring"=>"This string does not exist in the other language file",
    "random_number"=>"Random number: 4"
    ];

您可能已经猜到,不需要的结果位于hellorandom_number - 索引中。最好它应该仍然是"hello"=>"Hej {$name}!""random_number"=>"Random number: ".rand(1,10),但显然由于PHP解析数组值而发生这种情况,这基本上告诉我这是错误的策略。

通缉结果:

<?php return [
    "yes"=>"Ja",
    "no"=>"Nej",
    "hello"=>"Hej {$name}!",
    "newstring"=>"This string does not exist in the other language file",
    "random_number"=>"Random number: ".rand(1,10)
    ];

&#34;我是怎么做的?&#34;

知道怎么解决这个问题吗?我可以file_get_contents()并做一些正则表达式,但我担心其中涉及太多错误来源。

提前致谢!

修改

有些人建议使用单引号。虽然这实际上回答了我的问题,但我意识到我不够精确;当Language类处理文件时,我希望解析值(正常行为) - 但只有当我运行merge-script时,我才希望实际的文字变量引用保持不变。

编辑2 - 临时解决方法

在我找到适当的解决方案之前,我只是运行基本语言的数组,检查我尝试填充缺失键的语言中的关键存在 - 并附加一个评论这些文件的底部。

1 个答案:

答案 0 :(得分:1)

修改:请参阅OP的评论。这是事实,但不是他的问题的答案:)

您应该使用单引号而不是双引号:

<?php return [
"yes"=>'Yes',
"no"=>'No',
"hello"=>'Hello {$name}!'
"newstring"=>'This string does not exist in the other language file'
];

PHP仅解析双引号内的变量。

相关问题