如何用 PHP 中的值替换字符串中的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15065387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I replace a variable in a string with the value in PHP?
提问by open source guy
I have string like this in database (the actual string contains 100s of word and 10s of variable):
我在数据库中有这样的字符串(实际字符串包含 100 个单词和 10 个变量):
I am a {$club} fan
I echo this string like this:
我像这样回显这个字符串:
$club = "Barcelona";
echo $data_base[0]['body'];
My output is I am a {$club} fan. I want I am a Barcelona fan. How can I do this?
我的输出是I am a {$club} fan. 我要I am a Barcelona fan。我怎样才能做到这一点?
回答by Husman
Use strtr. It will translate parts of a string.
使用strtr. 它将翻译字符串的一部分。
$club = "Barcelona";
echo strtr($data_base[0]['body'], array('{$club}' => $club));
For multiple values (demo):
对于多个值(演示):
$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);
Program Output:
程序输出:
I am a Barcelona fan.
回答by tiffin joe
/**
* A function to fill the template with variables, returns filled template.
*
* @param string $template A template with variables placeholders {$variable}.
* @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 . ' ');
}
回答by Moises Gumbs
I would suggest the sprintf()function.
我建议使用sprintf()函数。
Instead of storing I am a {$club} fan, use I am a %s fan, so your echocommand would go like:
而不是存储I am a {$club} fan,使用I am a %s fan,所以你的回声命令会像:
$club = "Barcelona";
echo sprintf($data_base[0]['body'],$club);
Output: I am a Barcelona fan
输出:我是巴塞罗那球迷
That would give you the freedom of use that same code with any other variable (and you don't even have to remember the variable name).
这将使您可以自由地将相同的代码与任何其他变量一起使用(您甚至不必记住变量名称)。
So this code is also valid with the same string:
所以这段代码也适用于相同的字符串:
$food = "French fries";
echo sprintf($data_base[0]['body'], $food);
Output: I am a French fries fan
输出:我是炸薯条迷
$language = "PHP";
echo sprintf($data_base[0]['body'], $language);
Output: I am a PHP fan
输出:我是 PHP 粉丝
回答by zamnuts
You are looking for nested string interpolation. A theory can be read in the blog post Wanted: PHP core function for dynamically performing double-quoted string variable interpolation.
您正在寻找嵌套字符串插值。可以在博客文章Wanted:用于动态执行双引号字符串变量插值的 PHP 核心函数中阅读一个理论。
The major problem is that you don't really know all of the variables available, or there may be too many to list.
主要问题是您并不真正了解所有可用的变量,或者可能有太多无法一一列出。
Consider the following tested code snippet. I stole the regex from Mohammad Mohsenipur.
考虑以下经过测试的代码片段。我从 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";
Your code may be:
您的代码可能是:
$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;
回答by Robert Russell
if (preg_match_all('#$([a-zA-Z0-9]+)#', $q, $matches, PREG_SET_ORDER));
{
foreach ($matches as $m)
{
eval('$q = str_replace(\'' . $m[0] . '\', $' . $m[1] . ', $q);');
}
}
This matches all $variables and replaces them with the value.
这匹配所有 $variables 并用值替换它们。
I didn't include the {}'s, but it shouldn't be too hard to add them something like this...
我没有包含 {},但添加它们应该不会太难...
if (preg_match_all('#\{$([a-zA-Z0-9]+)\}#', $q, $matches, PREG_SET_ORDER));
{
foreach ($matches as $m)
{
eval('$q = str_replace(\'' . $m[0] . '\', $' . $m[1] . ', $q);');
}
}
Though it seems a bit slower than hard coding each variable. And it introduces a security hole with eval. That is why my regular expression is so limited. To limit the scope of what eval can grab.
尽管它似乎比对每个变量进行硬编码要慢一些。它引入了一个带有 eval 的安全漏洞。这就是我的正则表达式如此有限的原因。限制 eval 可以抓取的范围。
I wrote my own regular expression tester with Ajax, so I could see, as I type, if my expression is going to work. I have variables I like to use in my expressions so that I don't need to retype the same bit for each expression.
我用 Ajax 编写了自己的正则表达式测试器,因此我可以在键入时查看我的表达式是否有效。我有我喜欢在表达式中使用的变量,这样我就不需要为每个表达式重新键入相同的位。
回答by David H.
I've found these approaches useful at times:
我发现这些方法有时很有用:
$name = 'Groot';
$string = 'I am {$name}';
echo eval('return "' . $string . '";');
$data = array('name' => 'Groot');
$string = 'I am {$data[name]}';
echo eval('return "' . $string . '";');
$name = 'Groot';
$data = (object)get_defined_vars();
$string = 'I am {$data->name}';
echo eval('return "' . $string . '";');
回答by homberghp
You can use a simple parser that replaces {$key} with a value from a map if it exists.
您可以使用简单的解析器将 {$key} 替换为地图中的值(如果存在)。
Use it like:
像这样使用它:
$text = templateWith('hello $item}', array('item' => 'world'...));`
My first version is:
我的第一个版本是:
/**
* Template with a string and simple map.
* @param string $template
* @param array $substitutions map of substitutions.
* @return string with substitutions applied.
*/
function templateWith(string $template, array $substitutions) {
$state = 0; // forwarding
$charIn = preg_split('//u', $template, -1, PREG_SPLIT_NO_EMPTY);
$charOut = array();
$count = count($charIn);
$key = array();
$i = 0;
while ($i < $count) {
$char = $charIn[$i];
switch ($char) {
case '{':
if ($state === 0) {
$state = 1;
}
break;
case '}':
if ($state === 2) {
$ks = join('', $key);
if (array_key_exists($ks, $substitutions)) {
$charOut[] = $substitutions[$ks];
}
$key = array();
$state = 0;
}
break;
case '$': if ($state === 1) {
$state = 2;
}
break;
case '\': if ($state === 0) {
$i++;
$charOut[] = $charIn[$i];
}
continue;
default:
switch ($state) {
default:
case 0: $charOut[] = $char;
break;
case 2: $key[] = $char;
break;
}
}
$i++;
}
return join('', $charOut);
}
回答by Jader A. Wagner
Here is my solution:
这是我的解决方案:
$club = "Barcelona";
$string = 'I am a {$club} fan';
preg_match_all("/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", $string, $matches);
foreach ($matches[0] as $key => $var_name) {
if (!isset($GLOBALS[$matches[1][$key]]))
$GLOBALS[$matches[1][$key]] = 'default value';
$string = str_replace($var_name, $GLOBALS[$matches[1][$key]], $string);
}
回答by mohammad mohsenipur
You can use preg_replace_callbackfor getting a variable name like:
您可以使用preg_replace_callback获取变量名称,例如:
$data_base[0]['body'] = preg_replace_callback(
'#{(.*?)}#',
function($m) {
$m[1] = trim($m[1], '$');
return $this->$m[1];
},
' ' . $data_base[0]['body'] . ' '
);
Attention: This code I wrote is for class($this);. You can declare a variable into the class. Then use this code for detecting the variables and replace them like:
注意:我写的这段代码是为class($this);. 您可以在类中声明一个变量。然后使用此代码检测变量并将它们替换为:
<?php
class a {
function __construct($array) {
foreach($array as $key => $val) {
$this->$key = $val;
}
}
function replace($str){
return preg_replace_callback(
'#{(.*?)}#', function($m) {$m[1] = trim($m[1], '$'); return $this->$m[1];},
' ' . $str . ' ');
}
}
$obj = new a(array('club' => 3523));
echo $obj->replace('I am a {$club} fan');
Output:
输出:
I am a 3523 fan
回答by Dipesh Parmar
Try the preg_replacePHP function.
试试preg_replacePHP 函数。
<?php
$club = "Barcelona";
echo $string = preg_replace('#\{.*?\}#si', $club, 'I am a {$club} fan');
?>

