rosia
rosia

Reputation: 229

php dynamic replacement with a std object

How can I make a dynamic replacement with a std object? I can't get how to use $1 in this case :( See below.

$lang->custom_name = "Me";
$lang->custom_email = "Me@me";

$html = "hello {{custom_name}} with  {{custom_email}} ";    

$html = preg_replace("/{{(custom_.*)}}/", $lang->{'$1'} , $html);

Upvotes: 1

Views: 86

Answers (1)

MatsLindh
MatsLindh

Reputation: 52852

Instead of using preg_replace, use preg_replace_callback as it'll make it possible to use any mechanism you want to supply a replacement value.

// create stdClass 
$obj = (object) ['custom_foo' => 'foo-repl', 'custom_bar' => 'bar-repl'];
$html = "{{custom_foo}} {{custom_bar}}";

$res = preg_replace_callback("#{{(custom_.*?)}}#", function ($m) use ($obj) {
  // m (match) contains the complete match in [0] and the sub pattern in [1].
  return $obj->{$m[1]};
}, $html);

var_dump($res); // string(17) "foo-repl bar-repl"

If you want to use this for handling localization values, there are other, always made libraries that handle both the definition files, translate tools, etc. Look into gettext and friends (and there are probably other modern alternatives in other frameworks).

Upvotes: 2

Related Questions