I came across the following code with replaces one variable in a language file however I would like it to be able to do multiple e.g. %1, %2, %3, etc... and not just one %s. I tried tweaking it to count each variable in the line the do the replace but some how not getting it to work
my _helper
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('line_with_arguments'))
{
function line_with_arguments($line, $swap)
{
return str_replace('%s', $swap, $line);
}
}
my controller
<?php
class Home extends CI_Controller
{
public function index()
{
$this->lang->load('test', 'english');
$this->load->helper('i18n');
echo line_with_arguments($this->lang->line('test'), 'Matt');
}
}
my lang file :
<?php $lang['test'] = 'Hello %s';
Try something like this using vsprintf()
:
// Method 1: pass an array
function my_lang($line, $args = array())
{
$CI =& get_instance();
$lang = $CI->lang->line($line);
// $lang = '%s %s were %s';// this would be the language line
return vsprintf($lang, $args);
}
// Outputs "3 users were deleted"
echo my_lang('users.delete_user', array(3, 'users', 'deleted'));
// Method 2: read the arguments
function my_lang2()
{
$CI =& get_instance();
$args = func_get_args();
$line = array_shift($args);
$lang = $CI->lang->line($line);
// $lang = '%s %s were %s';// this would be the language line
return vsprintf($lang, $args);
}
// Outputs "3 users were deleted"
echo my_lang2('users.delete_user', 3, 'users', 'deleted');
Use the first argument of the function to pass the line index, get the correct line from CI, and pass an array as the second param (method1) or the rest of the arguments as each variable (method2). See the docs on sprintf()
for formatting: http://www.php.net/manual/en/function.sprintf.php
CI's native lang()
function uses the second param to pass an HTML form element id
and will create a <label>
tag instead - not a great use of this function if you ask me. If you don't use the label feature, it might be a good idea to create a my_language_helper.php
and overwrite the lang()
function to do this stuff natively, instead of writing a new function.
Here is what my actual lang()
function looks like, I don't need the <label>
option so I overwrote the second param to accept a string or an array of variables instead:
// application/helpers/my_language_helper.php
function lang($line, $vars = array())
{
$CI =& get_instance();
$line = $CI->lang->line($line);
if ($vars)
{
$line = vsprintf($line, (array) $vars);
}
return $line;
}
Such an small, easy change for this benefit, I wish it were the default - I never use lang()
to output a <label>
tag, but need to pass variables to it frequently.