【问题标题】:Array merging: Keeping literal variables数组合并:保留文字变量
【发布时间】:2014-12-10 06:58:42
【问题描述】:

让我直接进入我的问题。

积累

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

lang/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)
];

lang/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-indexes 中。最好它仍然应该是"hello"=&gt;"Hej {$name}!""random_number"=&gt;"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)
    ];

“我是怎么做到的?”

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

提前致谢!

编辑

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

编辑 2 - 临时解决方法

在我找到合适的解决方案之前,我只是遍历基本语言的数组,检查我试图用缺失键填充的语言中是否存在键 - 并在底部附加注释这些文件。

【问题讨论】:

  • 所以你的问题是,你不想在字符串中插入变量?并将其视为文字字符串?
  • 你可以看看维基百科用于扩展的模型,所有语言都保存在一个文件中的关联数组中——你可以一次加载它们,然后很容易检查您选择的语言中是否存在短语,如果不存在,请使用“默认”语言中的短语。
  • @ialarmedalien - 这实际上是它现在的工作方式。我想要做的是将不存在的键合并到其他语言文件中,以便我知道需要翻译的内容。
  • @Ghost - 不,抱歉我不够精确。查看编辑后的帖子。
  • 如果在合并数组之前删除在{ 之后找到的每个$,然后再次添加它们会怎样?只是一个快速的想法......

标签: php arrays laravel laravel-4


【解决方案1】:

编辑:参见 OP 的评论。这是真的,但不是他问题的答案:)

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

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

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

【讨论】:

  • 正确;但我没有说清楚,对不起。在正常情况下(即当应用程序实际使用语言文件时)我希望它实际解析值。只有在运行合并脚本时我才需要文字变量名。
  • 啊当然:)...在那种情况下,这确实不是答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 2018-01-08
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
相关资源
最近更新 更多