Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用std对象动态替换php_Php_Preg Replace_Preg Replace Callback - Fatal编程技术网

用std对象动态替换php

用std对象动态替换php,php,preg-replace,preg-replace-callback,Php,Preg Replace,Preg Replace Callback,如何使用std对象进行动态替换? 在这种情况下,我不知道如何使用$1:( 见下文 $lang->custom_name = "Me"; $lang->custom_email = "Me@me"; $html = "hello {{custom_name}} with {{custom_email}} "; $html = preg_replace("/{{(custom_.*)}}/",

如何使用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\u replace
,而要使用
preg\u replace\u 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
和friends(在其他框架中可能还有其他现代的替代方案)。

什么是
$1
?(自定义)stdClass类似于$lang->custom\u variablename原始字符串是什么样子的?添加了一些代码以澄清我正在尝试一个包含preg\u match匹配项的循环,但我更喜欢这个:)谢谢@rosia还要确保您使用的是
*?
,以避免使模式变得贪婪。