更清楚的是,默认语言general_lang.php
中的这些行都不起作用:
$lang['general_welcome_message'] = 'Welcome, %s ( %s )';
或
$lang['general_welcome_message'] = 'Welcome, %1 ( %2 )';
我希望输出 Welcome, FirstName ( user_name )
。
我在https://stackoverflow.com/a/10973668/315550跟随了第二个(不接受)回答。
我在视图中写的代码是:
<div id="welcome-box">
<?php echo lang('general_welcome_message',
$this->session->userdata('user_firstname'),
$this->session->userdata('username')
);
?>
</div>
我使用codeigniter 2。
答案 0 :(得分:11)
您需要使用php的sprintf函数(http://php.net/manual/en/function.sprintf.php)
来自http://ellislab.com/forums/viewthread/145634/#749634的示例:
//in english
$lang['unread_messages'] = "You have %1$s unread messages, %2$s";
//in another language
$lang['unread_messages'] = "Hi %2$s, You have %1$s unread messages";
$message = sprintf($this->lang->line(‘unread_messages’), $number, $name);
答案 1 :(得分:1)
我像这样扩展了Code CI_Lang类..
class MY_Lang extends CI_Lang {
function line($line = '', $swap = null) {
$loaded_line = parent::line($line);
// If swap if not given, just return the line from the language file (default codeigniter functionality.)
if(!$swap) return $loaded_line;
// If an array is given
if (is_array($swap)) {
// Explode on '%s'
$exploded_line = explode('%s', $loaded_line);
// Loop through each exploded line
foreach ($exploded_line as $key => $value) {
// Check if the $swap is set
if(isset($swap[$key])) {
// Append the swap variables
$exploded_line[$key] .= $swap[$key];
}
}
// Return the implode of $exploded_line with appended swap variables
return implode('', $exploded_line);
}
// A string is given, just do a simple str_replace on the loaded line
else {
return str_replace('%s', $swap, $loaded_line);
}
}
}
即。在您的语言文件中:
$lang['foo'] = 'Thanks, %s. Your %s has been changed.'
无论你想使用它(控制器/视图等)
echo $this->lang->line('foo', array('Charlie', 'password'));
将产生
Thanks, Charlie. Your password has been changed.
这可以处理单个&#39;交换&#39;以及多个
它也不会打破现有的$this->lang->line
来电。