【问题标题】:php dynamic replacement with a std object用std对象动态替换php
【发布时间】:2021-02-20 11:16:58
【问题描述】:

如何使用 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);

【问题讨论】:

  • 什么是$1
  • (custom_.*) stdClass 就像 $lang->custom_variablename
  • 原始字符串长什么样子?
  • 添加了更多代码来澄清

标签: php preg-replace preg-replace-callback


【解决方案1】:

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

【讨论】:

  • 我正在尝试使用 preg_match 匹配的循环,但我更喜欢这个 :) 谢谢!
  • @rosia 还要确保使用.*? 以避免使模式变得贪婪。
猜你喜欢
  • 2010-09-26
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 2012-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多