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).