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():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.phpCI’s native
lang()function uses the second param to pass an HTML form elementidand 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 amy_language_helper.phpand overwrite thelang()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: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.