valiD
valiD

Reputation: 359

preg_replace and use value in variable name

I have the following code:

<?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;   

?>

My new string should be HHH100200

I have added $depth variable so that you'll see that my string will not always use the same variables. I am pretty close on doing this but cannot create the variable name;

Also - I am not familiar with regex - I only want to allow a-zA-Z0-9 inside the brackets.

Upvotes: 2

Views: 614

Answers (2)

valiD
valiD

Reputation: 359

Thank you, @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;

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Using regex here is not the way to go, use an array with strtr or str_replace:

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

$str1 = strtr($str1, $trans); 

Upvotes: 1

Related Questions