带参数的多语言脚本


Multilingual script with parameters

我一直在制作一个多语言脚本。我已经让它完美地工作了,有一个带有语言变量的数组。每种语言都有自己的变量文件。脚本根据用户选择的语言决定要加载的文件。

这是我在每个语言文件中的内容:

$lang = array();
$lang['var1'] = "Some text here";
$lang['var2'] = "Some text here";
...
$lang['var20'] = "Some text here";

现在我想让它更加动态并包含参数。我在 vBulletin 语言模板中看到它,有这样的东西:text text text {1} text text text {2} text text.

我想要这段文字:Hello {1}, this is the User CP.参数应该是动态的,每个用户都不同。

怎么做?

这取决于

你想如何使用它,但你可以做的是,例如,使用printfsprintf作为输出:

语言文件:

$lang['varxx'] = 'Hello %s, this is the User CP';

使用它的脚本:

$name = "test user";
printf($lang['varxx'], $name);
$modified_string = sprintf($lang['varxx'], $name);

通常使用包装器函数。如果您到目前为止一直直接访问$lang阵列,则必须进行调整。

而且这样做是相当困难的:

 function t ($textid) {
      $text = $GLOBALS["lang"][$textid];
      $args = func_get_args();
      $text = preg_replace('#'{('d+)'}#e', '$args[$1]', $text);
      return $text;
 }

不过,您可以使用另一种模式方案来避开正则表达式。

用法很简单:

 print t("var1", "placeholder", ...);
$lang = array();
$lang['var1'] = "Hello %1$s, here's a %2$s";
echo vsprintf($lang['var1'], array("John", "cookie"));

输出:

Hello John, here's a cookie

更多关于 sprintf 和 vsprintf 的信息