PHP替换动态变量

时间:2019-04-29 10:11:05

标签: php regex

我正在以这种方式替换动态字符串,并且它可以正常工作。

<?php
$data = 'wow@example.org|Foo|2019|....|x_Param';
$parts = explode("|", $data);

$text = 'Hello [-param_1-] Your email is [-param_0-]';
$new_text = str_replace('[-param_0-]', $parts[0], $text);
$new_text = str_replace('[-param_1-]', $parts[1], $new_text);
$new_text = str_replace('[-param_2-]', $parts[2], $new_text);
# .... param_X

echo $new_text;
# Out: Hello Foo Your email is wow@example.org

?>

如何改进它,我的操作方式效率不高,如果有9999.X,如何更换它。.

感谢您的帮助

Edi-解决方案:

<?php
$data = 'wow@example.org|Foo|2019|....|x_Param';
$parts = explode("|", $data);

$text = 'Hello [-param_1-] Your email is [-param_0-]';

//$text = 'Hello [-param_1-] Your email is [-param_0-]';

$new_text = $text;
foreach($parts as $i => $part){
    $new_text = str_replace('[-param_'.$i.'-]', $part, $new_text);  
}

echo $new_text;


?>

2 个答案:

答案 0 :(得分:2)

那么,您可以只使用一个str_replace,就像这样:

<?php
$data = 'wow@example.org|Foo|2019|....|x_Param';
$parts = explode("|", $data);

$text = 'Hello [-param_1-] Your email is [-param_0-]';
$params = ['[-param_0-]', '[-param_1-]', '[-param_2-]'];
$new_text = str_replace($params, $parts, $text);

echo $new_text;
# Out: Hello Foo Your email is wow@example.org

?>

是的,str_replace()将接受数组。

如果您有大量参数,则可以使用循环生成$params数组,但就我个人而言,我将使用更有意义的东西。因此,我将拥有[-param_0-]而不是%%email%%,依此类推。

答案 1 :(得分:0)

<?php
$data = 'wow@example.org|Foo|2019|....|x_Param';
$parts = explode("|", $data);

$text = 'Hello [-param_1-] Your email is [-param_0-]';

//$text = 'Hello [-param_1-] Your email is [-param_0-]';

$new_text = $text;
foreach($parts as $i => $part){
    $new_text = str_replace('[-param_'.$i.'-]', $part, $new_text);  
}

echo $new_text;


?>