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

后端 未结 2 1081
迷失自我
迷失自我 2021-01-28 14:20

I have translate function t($var);

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

where $this->words is

相关标签:
2条回答
  • 2021-01-28 14:49

    You can define the t function like below :

    function t($array)
    {
        return sprintf($array['sentence'],$array['word1'],$array['word1']);
    }
    

    Where array is :

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

    Call the function : echo t($array);

    0 讨论(0)
  • 2021-01-28 14:52

    I've seen people recommend using sprintf but personally I'd recommend using vsprintf: http://www.php.net/manual/en/function.vsprintf.php

    function t($word, $vars = array()) {
      return vsprintf($this->words[$word], $vars);
    }
    

    This allows you to pass in an array of variables instead of passing them in as separate parameters.

    Generally translate functions will first check for a translation and if not found just return the lookup key.

    function t($word, $vars = array()) {
      return isset($this->words[$word]) ? vsprintf($this->words[$word], $vars) : $word;
    }
    
    0 讨论(0)
提交回复
热议问题