用std对象动态替换php

问题描述

如何使用 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 和朋友们(可能还有其他现代替代品在其他框架中)。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...