在数组的字符串中设置参数

I have a function language($tag) that requires a file lang.php which contains an array called $lang which contains some parameters. In particular a string $lang['message']. After some execution lines it returns $lang['message'].

The $lang array is defined as follows:

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

Now let's say I'd like to be able to set parameters inside $lang['message'] that I should be able to define on language($tag, $parameters). And these parameters should set a var inside $lang['message'] such as:

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

How is the best way of organize language($tag, $parameters) so that what is in $parameters sets $1 in $lang['message']?

If you didn't understand I'd like to be able to call language($tag, 'post') and make it return 'This is a post'.

How about saving the strings as printf templates, eg

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

You can then use vsprintf to pass an array of value substitutions, eg

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

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

One solution could be using sprintf().

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

And you just use it like this:

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

Please read the manual page of sprintf() to see its numerous capabilities.

I would probably go with sprintf() for my language function.

The solution would probably look like this:

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

And:

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);
}

This way you can use it like this:

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