我在数据库中有这样的字符串(实际字符串包含100个单词和10个变量)
i am a {$club} fan
Run Code Online (Sandbox Code Playgroud)
我像这样回应这个字符串
$club = "Barcelona";
echo $data_base[0]['body'];
Run Code Online (Sandbox Code Playgroud)
我的输出是 i am a {$club} fan.我想我 i am a Barcelona fan
怎么能这样做?
Hus*_*man 72
使用strtr它将翻译字符串的一部分.
$club = "Barcelona";
echo strtr($data_base[0]['body'], array('{$club}' => $club));
Run Code Online (Sandbox Code Playgroud)
对于多个值(演示):
$data_base[0]['body'] = 'I am a {$club} fan.'; // Tests
$vars = array(
'{$club}' => 'Barcelona',
'{$tag}' => 'sometext',
'{$anothertag}' => 'someothertext'
);
echo strtr($data_base[0]['body'], $vars);
Run Code Online (Sandbox Code Playgroud)
节目输出:
I am a Barcelona fan.
Run Code Online (Sandbox Code Playgroud)
小智 7
/**
* A function to fill the template with variables, returns filled template.
*
* @param string $template A template with variables placeholders {$varaible}.
* @param array $variables A key => value store of variable names and values.
*
* @return string
*/
public function replaceVariablesInTemplate($template, array $variables){
return preg_replace_callback('#{(.*?)}#',
function($match) use ($variables){
$match[1]=trim($match[1],'$');
return $variables[$match[1]];
},
' '.$template.' ');
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个答案仍然得到了赞成,所以人们需要意识到下面的代码片段中存在的朴素插值技术存在安全漏洞。攻击者可以在输入字符串中包含任意变量,这将泄露有关服务器的信息或运行时变量寄存器中的其他数据。这是由于通用表达式搜索的执行方式所致,它会查找任意变量名称模式,然后在后续调用中逐字使用这些变量名称compact。这会导致客户端控制服务器端行为,类似于eval. 我把这个答案留给后人。
您正在寻找嵌套字符串插值。可以在博客文章Wanted:用于动态执行双引号字符串变量插值的 PHP 核心函数中阅读理论。
主要问题是您并不真正了解所有可用的变量,或者可能太多而无法列出。
考虑以下经过测试的代码片段。我从 Mohammad Mohsenipur 那里偷了正则表达式。
$testA = '123';
$testB = '456';
$testC = '789';
$t = '{$testA} adsf {$testB}adf 32{$testC} fddd{$testA}';
echo 'before: ' . $t . "\n";
preg_match_all('~\{\$(.*?)\}~si', $t, $matches);
if ( isset($matches[1])) {
$r = compact($matches[1]);
foreach ( $r as $var => $value ) {
$t = str_replace('{$' . $var . '}', $value, $t);
}
}
echo 'after: ' . $t . "\n";
Run Code Online (Sandbox Code Playgroud)
您的代码可能是:
$club = 'Barcelona';
$tmp = $data_base[0]['body'];
preg_match_all('~\{\$(.*?)\}~si', $tmp, $matches);
if ( isset($matches[1])) {
$r = compact($matches[1]);
foreach ( $r as $var => $value ) {
$tmp = str_replace('{$' . $var . '}', $value, $tmp);
}
}
echo $tmp;
Run Code Online (Sandbox Code Playgroud)
我会建议sprintf()功能。
而不是存储i am a {$club} fanuse i am a %s fan,因此您的echo命令将如下所示:
$club = "Barcelona";
echo sprintf($data_base[0]['body'],$club);
Run Code Online (Sandbox Code Playgroud)
输出:我是巴塞罗那球迷
这样,您就可以将同一代码与其他任何变量一起使用(而您甚至不必记住变量名)。
因此此代码对相同的字符串也有效:
$food = "French Fries";
echo sprintf($data_base[0]['body'],$food);
Run Code Online (Sandbox Code Playgroud)
输出:我是薯条迷
$language = "PHP";
echo sprintf($data_base[0]['body'],$language);
Run Code Online (Sandbox Code Playgroud)
输出:我是PHP迷