目前我正在一个需要支持多语言的项目上工作,我写了一个简单的函数来做到这一点,这里问是否有更好的方法来返回语言var使用包括langfile?
这是我写翻译文件的地方。
class OhHelper
{
//.... Other function
public static function t($filename, $msg = '', $arr = array())
{
$lang = defined('lang_select') ? lang_select : lang;
$file = ROOT . DS . 'language' . DS . $lang . DS . $filename . '.php';
if(file_exists($file))
{
$lang = include $file;
if($msg == '')
{
//return the whole language array
return $lang;
}
if(array_key_exists($msg, $lang))
{
if(preg_match('/'{['d+]'}/', $lang[$msg], $matched))
{
if(count($matched) > 0)
{
$langReplace = $lang[$msg];
foreach($matched as $key => $var)
{
$langReplace = preg_replace('/'{['d+]'}/', $arr[$key], $langReplace);
}
return $langReplace;
}
}
else
{
//return the selected lang(there is no {'d} to replace
return $lang[$msg];
}
}
}
return 'lang file not found';
}
}
这里是语言文件
return array(
'welcome good to see you again' => 'Welcome {1}, good to see you again',
'good bye see you again' => 'Bye {1}, see you',
);
下面是我如何调用并成功替换
内容echo OhHelper::t('general', 'welcome good to see you again', array('username'));
目前这个函数是可行的,但我正在寻找更好的性能,我猜用这个重复每个文本OhHelper::t()是真的很慢,当有很多内容(我猜)
我在MVC模式下做所以我想另一种方式
每个控制器结构$this->lang = OhHelper('controller', ")
但是这样我就不能用动态内容替换{1}模式,只能做一些像
这样的事情echo $this->lang['welcome']; echo ' '; echo 'username'; echo $this->lang['see you again'];
我使用像你一样的标签,但不是数字,它不需要正则表达式。为每次调用运行正则表达式可能会降低应用程序的速度。
你可以用{username}
代替{1}
,当你调用:
echo OhHelper::t('general', 'welcome good to see you again', array('username'));
你应该使用数组的键来代替
echo OhHelper::t('general', array('username' => 'welcome good to see you again'));
,在OhHelper class
中,你只迭代数组参数和str_replace
。
后来编辑:
请注意,除非没有其他方法,否则永远不要使用正则表达式。尽量避免它们,因为如果你不优化它们,它们会非常慢。