Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP将字符串中的通配符(%s,%d)替换为变量_Php - Fatal编程技术网

PHP将字符串中的通配符(%s,%d)替换为变量

PHP将字符串中的通配符(%s,%d)替换为变量,php,Php,我有翻译函数t($var) 其中$this->words是数组 $this->words = array( 'word1' => 'word', 'word2' => 'something' ); 我将函数用作 输出为:word 我的目标是使用通配符%s,%d,%f用变量替换它们 例如: $this->words = array( 'word1' => 'word', 'word2' => 'something', '

我有翻译函数
t($var)

其中
$this->words
是数组

$this->words = array(
    'word1' => 'word',
    'word2' => 'something'
);
我将函数用作
输出为:
word

我的目标是使用通配符%s%d%f用变量替换它们

例如:

$this->words = array(
    'word1' => 'word',
    'word2' => 'something',
    'sentence' => 'Hello, my name is %s. I am %d years old.'
);
然后将变量解析为
t()
函数

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

但是该函数不能处理每种类型的变量中的一个以上。

我看到有人建议使用
sprintf
,但我个人建议使用
vsprintf

这允许您传入一个变量数组,而不是将它们作为单独的参数传入

通常,translate函数将首先检查翻译,如果没有找到,则返回查找键

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

我见过有人建议使用
sprintf
,但我个人建议使用
vsprintf

这允许您传入一个变量数组,而不是将它们作为单独的参数传入

通常,translate函数将首先检查翻译,如果没有找到,则返回查找键

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

您可以按如下方式定义t函数:

function t($array)
{
    return sprintf($array['sentence'],$array['word1'],$array['word1']);
}
其中,数组为:

$array = array(
    'word1' => 'word',
    'word2' => 'something',
    'sentence' => 'Hello, my name is %s. I am %d years old.'
);
调用函数:
回波t($阵列)

您可以如下定义t函数:

function t($array)
{
    return sprintf($array['sentence'],$array['word1'],$array['word1']);
}
其中,数组为:

$array = array(
    'word1' => 'word',
    'word2' => 'something',
    'sentence' => 'Hello, my name is %s. I am %d years old.'
);
调用函数:
回波t($阵列)

此解决方案的问题是,您只能传入预定义的字数(在本例中为2)。您可以使用
eval()
执行动态操作,但不能。有一个vsprintf,它采用了一个值数组,如我的回答所示。这个解决方案的问题是,您只能传入预定义的字数(在本例中为2)。您可以使用
eval()
执行动态操作,但不能。有一个vsprintf,它接受一个值数组,如我的答案所示。