You need a simple (very simple) "template system", but there are two template templates in your problem.
- Convert "
Hello $X! " To " Hello Jonh! " Or " Hello Maria! " By specifying $ X. (PHP does this for you in line declarations). - Choose the appropriate template: “
Hello $X! ” For English, “ ¡Hola $X! ” For Spanish.
Element 1 is simpler, but the order of the algorithm is 2.1 (clause 2 of clause 1). For this simple task, you do not need a regular expression (to reuse the "string with place owner" PHP).
Illustrating
For element 1, the easiest way is to declare a specialized function to say "Hello",
// for any PHP version. function template1($name) { return "<p>Hello $name!</p>";} print template1("Maria");
For point 2, you need a generalization of what PHP does for you, by closing,
header('Content-Type: text/html; charset=utf-8'); // only for remember UTF8. // for PHP 5.3+. Use function generalTemplate1($K) { // $K was a literal constant, now is a customized content. return function($name) use ($K) {return "<p>$K $name!</p>"; }; } // Configuring template1 (T1) for each language: $T1_en = generalTemplate1('Hello'); // english template $T1_es = generalTemplate1('¡Hola'); // spanish template // using the T1 multilingual print $T1_en('Jonh'); // Hello Jonh! print $T1_es('Maria'); // ¡Hola Maria!
For additional templates, use generalTemplate2 (), generalTemplate3 (), etc .; $T2_en , $T2_es , $T2_fr , $T3_en , $T3_es , etc.
Decision
Now, for rational use, you like to use arrays ... Well, there is a problem with the file structure, and more than 1 level of generalization. Cost is a variable name parser for place owners. I used a simple regular expression with preg_replace_callback ().
function expandMultilangTemplate($T,$K,$lang,$X) {
I tested this script with PHP5, but it works with the old ones (PHP 4.0.7 +).
About "multilingual files": if your translations are in files, you can use somthing like
$K = getTranslation('translationFile.txt'); function getTranslation($file,$sep='|') { $K = array(); foreach (file($file) as $line) { list($lang,$words) = explode($sep,$line); $K[$lang]=$words; } }
and file as
en|Hello es|¡Hola
Simplest with PHP 5.3
If you are using PHP 5.3+, there’s a simple and elegant way to express this “simple multilingual template system”,
function expandMultilangTemplate($T,$K,$lang,$X) { $T = str_replace('{#K}',$K[$lang],$T); $T = preg_replace_callback( '/@([az]+)/', function($m,$X=NULL) use ($X) { return array_key_exists($m[1],$X)? $X[$m[1]]: ''; }, $T ); return $T; }