问题描述
如何使用 std 对象进行动态替换? 在这种情况下,我不知道如何使用 $1 :( 见下文。
$lang->custom_name = "Me";
$lang->custom_email = "Me@me";
$html = "hello {{custom_name}} with {{custom_email}} ";
$html = preg_replace("/{{(custom_.*)}}/",$lang->{'$1'},$html);
解决方法
不要使用 preg_replace
,而是使用 preg_replace_callback
,因为它可以使用您想要提供替换值的任何机制。
// 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"
如果你想用它来处理本地化值,还有其他的、总是制作的库来处理定义文件、翻译工具等。看看 gettext
和朋友们(可能还有其他现代替代品在其他框架中)。