简体   繁体   English

PHP的foreach替换变量

[英]php foreach replace variables

I want to use a template file, where i am using {value} as markers to replace that with a value. 我想使用一个模板文件,其中我使用{value}作为标记来将其替换为一个值。

The variable is set like $order and I want to replace it in the template where there is {order}. 该变量设置为$ order,我想在有{order}的模板中替换它。

There are about 50 of these variables I want to replace. 这些变量中大约有50个我要替换。

Is there a way to do this automaticly? 有没有一种方法可以自动执行此操作?

$text = file_get_contents("bol_files/order_template.txt");
    $text = str_replace("{ordernummer}",$bestelnummer, $text);
    $text = str_replace("{verzendwijze}",$verzendwijze, $text);
    echo $text;

You could use strtr function. 您可以使用strtr函数。

$text = file_get_contents("bol_files/order_template.txt");
$trans = array(
    '{ordernummer}' => $bestelnummer, 
    '{verzendwijze}'   => $verzendwijze,
    ......
);
echo strtr($text, $trans);

Update: If your rule is fixed (replace {var_name} with $var_name ), then you could use regex replace. 更新:如果您的规则是固定的(将{var_name}替换为$var_name ),则可以使用正则表达式替换。

echo preg_replace('/\{([^}]+)\}/e',  '${\'$1\'}' , $text );

Check the example. 检查示例。

Addition: but e marker is deprecated (you could use preg_replace_callback instead, but in that way, you need to import these variables into the scope of the callback function), I think you'd better hold the data in an array instead of separate variables, even if you could use get_defined_vars . 另外:但是不推荐使用e标记(您可以改用preg_replace_callback ,但是那样的话,您需要将这些变量导入回调函数的范围内),我认为最好将数据保存在数组中而不是单独的变量中,即使您可以使用get_defined_vars

IMO, the easiest would be to collect the template vars in an array in the first place instead of using individual variables. IMO, 最简单的方法是首先将模板变量收集到数组中,而不是使用单个变量。 Then you could simply pass the array as a whole to str_replace . 然后,您可以将整个数组简单地传递给str_replace

If the above is not an option, you could use 如果以上都不是,则可以使用

Example: 例:

$a = 'foo';
$b = 'bar';
$c = 'baz';

$template = '{a} to the {b} to the {c}';

foreach (get_defined_vars() as $key => $val) {
     if (is_scalar($val)) {
         $template = str_replace('{' . $key . '}', $val, $template);
     }
}
echo $template; // prints 'foo to the bar to the baz';

Demo 演示版

Alternative that does the same: 具有相同功能的替代方法:

$a = 'foo';
$b = 'bar';
$c = 'baz';

$template = '{a} to the {b} to the {c}';

$scopeVars = array_filter(get_defined_vars(), 'is_scalar');
$templateMarker = preg_replace('/^.*$/', '{$0}', array_keys($scopeVars));
echo str_replace($templateMarker, $scopeVars, $template);

Demo 演示版

But note that this is potentially insecure when you let other people provide the template markers in the template. 但是请注意,当您让其他人在模板中提供模板标记时,这可能是不安全的。 Since get_defined_vars gets you all the vars in the current scope , someone could try to guess variables that are not template values which might potentially contain sensitive data. 由于get_defined_vars可以获取当前范围内的所有var ,因此有人可以尝试猜测不是模板值的变量,这些变量可能包含敏感数据。 Up to you to evaluate that risk. 由您来评估该风险。

Also note that I have added a check to see whether the scope variables hold a scalar value because if there is objects or arrays in the scope vars, PHP will complain about not being able to convert those to strings in str_replace . 还要注意,我添加了一个检查以查看范围变量是否具有标量值,因为如果范围var中存在对象或数组,PHP将抱怨无法在str_replace中将其转换为字符串。

str_replace can take arrays as arguments: str_replace可以将数组作为参数:

$text = str_replace(array_keys($replaceArray), $replacearray, $text);

where $replaceArray is an associative array 其中$ replaceArray是一个关联数组

$replaceArray = (
  "{ordernummer}" => $bestelnummer,
  "{verzendwijze}" => $verzendwijze,
 and so on
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM