2

更清楚地说,默认语言的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。

4

2 回答 2

15

您将需要使用 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);
于 2013-07-16T08:41:45.440 回答
2

我像这样扩展了 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);
        }
    }
}

IE。在您的语言文件中:

$lang['foo'] = 'Thanks, %s. Your %s has been changed.'

以及您想在哪里使用它(控制器/视图等)

echo $this->lang->line('foo', array('Charlie', 'password'));

会产生

Thanks, Charlie. Your password has been changed.

这可以处理单个“交换”以及多个

它也不会破坏任何现有的对$this->lang->line.

于 2015-07-02T11:39:08.800 回答