samedi 28 juin 2014

PHP replace wildcards (%s, %d) in string with vars


Vote count:

0




I have translate function t($var);



function t($word) {
return $this->words[$word];
}


where $this->words is array



$this->words = array(
'word1' => 'word',
'word2' => 'something'
);


I am using functions as <?php echo t('word1'); ?> and output is : word


My goal is to use wildcards %s, %d, %f to replace them with variables. Example:



$this->words = array(
'word1' => 'word',
'word2' => 'something',
'sentence' => 'Hello, my name is %s. I am %d years old.'
);


Then parse variables into t() function.



<?php echo t('sentence', array('Mike', 99));


So output will be: Hello, my name is Mike. I am 99 years old.


My Work so far:



function t($word, $vars = array()) {
foreach ($vars as $key) {
if(is_string($key)){
$this->words[$word] = str_replace ('%s', $key, $this->words[$word]);
}
if(is_int($key)) {
$this->words[$word] = str_replace ('%d', $key, $this->words[$word]);
}
if(is_float($key)){
$this->words[$word] = str_replace ('%f', $key, $this->words[$word]);
}
}
return $this->words[$word];
}


But this function doesn't work with more than one of each type of variable.



asked 29 secs ago






Aucun commentaire:

Enregistrer un commentaire