2011-11-15 20 views
1

我有一個功能language($tag),它需要一個文件lang.php,它包含一個名爲$lang的數組,其中包含一些參數。特別是字符串$lang['message']。在一些執行行後,它返回$lang['message']在數組的字符串中設置參數

的$ LANG數組定義如下:

$lang[$tag] = array(
    'message' => 'This is a message', 
    ... 
); 

現在,讓我們說,我想能夠設置裏面$lang['message']參數,我應該能夠定義上language($tag, $parameters)。這些參數應該設置一個變種內$lang['message']如:

$lang[$tag] = array(
    'message' => 'This is a '. $1, 
    ... 
); 

如何最好地組織language($tag, $parameters),使什麼是$parameters$1$lang['message']

如果您不明白我希望能夠致電language($tag, 'post')並使其返回'This is a post'

回答

3

如何保存字符串作爲printf模板,如

$lang[$tag] = array(
    'message' => 'This is a %s' 
); 

然後可以使用vsprintf通過價值置換陣列,如

function language($tag, array $values) 
{ 
    // get $lang from somewhere 

    return vsprintf($lang[$tag]['message'], $values); 
} 
+0

+1'vsprintf中()'可能會更好。 – kapa

2

一個解決方案可以使用sprintf()

'message' => 'This is a %s', 

而你只是用它是這樣的:

sprintf($lang['message'], 'post'); 

請閱讀manual page of sprintf()看到它的許多功能。

2

我可能會用sprintf()去我語言功能。

的解決方案可能會是這樣的:

$lang = array(
    'stop' => 'Stop right there!', 
    'message' => 'This is a %s', 
    'double_message' => 'This is a %s with %s comments', 
    ... 
); 

和:

function language() 
{ 
    $lang = get_lang_from_file(); // You probably have the idea 
    $params = func_get_args(); 


    if(count($params) == 1) 
     return $lang[$params[0]]; 

    $params[0] = $lang[$params[0]]; 
    return call_user_func_array("sprintf", $params); 
} 

這樣你就可以使用它像這樣:

echo language('stop'); // outputs 'Stop right there!' 
echo language('message', 'message for you'); // outputs 'This is a message for you' 
echo language('double_message', 'message for you', '6'); // outputs 'This is a message for you with 6 comments 
+0

'vsprintf()'比'sprintf'好多了''call_user_func_array()' – Phil

+0

謝謝你的提示:) – Repox

相關問題