【问题标题】:preg_replace with array indexpreg_replace 与数组索引
【发布时间】:2015-12-29 11:32:10
【问题描述】:

我有一个关联数组和一个带有变量名称的文本,用这样的括号括起来:

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

我的数组是这样的:

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

(显然这个数组可以更大,我不知道里面的变量名)。这是我想要做的:我想用数组中的值替换消息中的 {var},如下所示:

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

有人知道怎么做吗?

非常感谢!

【问题讨论】:

  • 看看:preg_replace_callback()

标签: php regex preg-replace


【解决方案1】:

@Rizier123's comment 帮助了我,这是我用来解决问题的代码:

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

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 2010-10-28
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多