Php preg_替换并使用变量名中的值

Php preg_替换并使用变量名中的值,php,regex,preg-replace,Php,Regex,Preg Replace,我有以下代码: <?php $clasa = 'HHH'; $length = '100'; $width = 200; $depth = 300; $string1 = '{{clasa}}{{length}}{{width}}'; $string2 = '{{clasa}}{{length}}{{depth}}'; $string3 = '{{clasa}}_word{{length}},anything{{depth}}'; $new1 = preg_replace('/{

我有以下代码:

<?php

$clasa = 'HHH';
$length = '100';
$width = 200;
$depth = 300; 


$string1 = '{{clasa}}{{length}}{{width}}';
$string2 = '{{clasa}}{{length}}{{depth}}';
$string3 = '{{clasa}}_word{{length}},anything{{depth}}';

$new1 = preg_replace('/{{([a-zA-Z\_\-]*?)}}/', ${'"$1"'}, $string1);

echo $new1;   

?>

在这里使用正则表达式不是一个好办法,使用带有
strtrtr
stru-replace
的数组:

$trans = ['{{clasa}}'  => 'HHH',
          '{{length}}' => '100',
          '{{width}}'  => '200',
          '{{depth}}'  => '300'];

$str1 = strtr($str1, $trans); 
谢谢你,@Rizier123

<?php

$clasa = 'HHH';
$length = '100';
$width = 200;
$depth = 300; 


$string1 = '{{clasa}}{{length}}{{width}}';
$string2 = '{{clasa}}{{lenght}}{{depth}}';
$string3 = '{{clasa}}_word{{lenght}},anything{{depth}}';

//$new1 = preg_replace('/{{([a-zA-Z\_\-]*?)}}/', ${'"$1"'}, $string1);
$new1 = preg_replace_callback("/{{([a-zA-Z\_\-]*?)}}/", function($m){
    global ${$m["1"]};
    return ${$m["1"]};
}, $string1);

echo $new1;

如果要使用变量,请查看
preg\u replace\u callback()
,并且不要忘记PHP具有变量的函数作用域。然后,我必须声明全局变量,因为我不知道我将使用它。是的,这是正确的,但是你可以用变量来做。我没有使用任何“我只想在括号内允许a-zA-Z0-9”的意外括号:在这种情况下,你为什么要添加
-
?如果我知道这些变量是我将来要使用的所有变量,我就会这样做。