简体   繁体   English

带数组索引的preg_replace

[英]preg_replace with array index

I have an associative array, and a text with variables names inside, surrounded with brackets like this : 我有一个关联数组,里面有变量名称的文本,用这样的括号括起来:

$message = "The value of var is: {var} ...-";

My array is like this: 我的数组是这样的:

$array=array('var'=>$var);

(Obviously this array can be bigger, and I don't know the name of the variables inside of it). (显然这个数组可能更大,我不知道其中变量的名称)。 Here is what I'm trying to do: I want to replace the {var} in my message by it's value in my array, like this: 这是我正在尝试做的事情:我想用我的数组中的值替换我的消息中的{var},如下所示:

$newMessage = preg_replace('#\{(.+)\}#',$array["$1"],$message);

Anyone knows how to do it? 谁知道怎么做?

Thank you very much! 非常感谢你!

@Rizier123's comment helped me, here's the code I used to solve my problem: @ Rizier123的评论帮助了我,这是我用来解决问题的代码:

$newMessage=preg_replace_callback('#\{(.+)\}#',function($match)use($array){
    return $array[$match[1]];
},$message);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM