#1320 closed Enhancement (fixed)
Enhance elgg_echo to use vsprintf with argument swapping
| Reported by: | milan | Owned by: | brettp |
|---|---|---|---|
| Priority: | normal | Milestone: | Elgg 1.8.0 |
| Component: | Core | Version: | 1.6 |
| Severity: | minor | Keywords: | |
| Cc: | brettp | Difficulty: |
Description
After looking at the new coding conventions I saw that inline variable interpolation was preferred over breaking up a string with variables. But I was thinking as elgg supoorts multiple languages then elgg_echo could easily be enhanced to use vsprintf so that variables could be imbedded to a string using it's format and argument swapping.
So if you were to use this elgg_echo function:
function elgg_echo($message_key, $language = "", $printf_args = array()) {
global $CONFIG;
static $CURRENT_LANGUAGE;
if ((!$CURRENT_LANGUAGE) && (!$language))
$CURRENT_LANGUAGE = $language = get_language();
else
$language = $CURRENT_LANGUAGE;
if (isset($CONFIG->translations[$language][$message_key])) {
$message_key = $CONFIG->translations[$language][$message_key];
} else if (isset($CONFIG->translations["en"][$message_key])) {
$message_key = $CONFIG->translations["en"][$message_key];
}
// arguments in the sprintf string should use argument swapping
if ($printf_args && is_array($printf_args)) {
$message_key = vsprintf($message_key, $printf_args);
}
return $message_key;
}
so you could run some code like this:
// stored in the language file...
// elgg:language:monkey = 'The %2$s contains %1$d monkeys. That\'s a nice %2$s full of %1$d monkeys.'
echo elgg_echo('elgg:language:monkey', 'en', array('10', 'cage'));
which would allow language translations where the words in the sentence could be arranged in a different order.
Change History (5)
comment:1 Changed 4 years ago by brettp
- Milestone changed from Elgg 1.7 to Elgg 1.8
- Owner set to brettp
- Status changed from new to assigned
- Summary changed from Enhance elgg_echo to use vsprintf to Enhance elgg_echo to use vsprintf with argument swapping
comment:2 Changed 3 years ago by brettp
comment:3 Changed 3 years ago by brettp
(In [svn:7227]) Refs #1320. Updated core to use elgg_echo()'s native string replacement.
comment:4 Changed 3 years ago by brettp
- Resolution set to fixed
- Status changed from assigned to closed
(In [svn:7229]) Fixes #1320: Bundled mods use elgg_echo()'s internal string substitution.
comment:5 Changed 3 years ago by brettp
If anyone is interested, I used the regex:
sprintf\((elgg_echo\([^\)]*)\),(\s+)?(.*)\)([,;\n])
to find the instances and
$1,$2array($3))$4
to replace them. This doesn't work for any embedded function calls or if the entire call is an argument to a function, so be careful.

(In [svn:7226]) Refs #1320: elgg_echo() has built-in sprintf support.