【问题标题】:PHP Preg Replace replacement arrayPHP Preg 替换替换数组
【发布时间】:2012-01-26 13:00:39
【问题描述】:

好的,我正在尝试这样做:

preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);

现在我知道这是不可能的,但是我想知道是否有办法做到这一点,因为我尝试使用 create_function 但是,$templateVariables 是它所在函数的局部变量在里面,所以我不能从 create_function 中访问 $templateVariables,所以我有点卡在这里。我宁愿不必找到匹配项找出替换它们的内容,然后再次找到它们进行替换,这似乎是非常低效的。那么无论如何我可以从匿名函数中获取局部变量吗?或者有人有什么好的建议吗?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    你需要使用 e 正则表达式修饰符:

    preg_replace("/\{([a-zA-Z0-9_]+)\}/e", "\$templateVariables['\\1']", $templateString);
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $vars = array(
          "test" => "Merry Christmas",
      );
      $string = "test {test} test";
      $string = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function($match) use ($vars) {
          return isset($vars[$match[1]]) ? $vars[$match[1]] : $match[0];
      }, $string);
      echo $string;
      

      它应该输出:

      测试圣诞快乐测试

      你可以在这里看到一个工作示例http://codepad.viper-7.com/2ZNNYZ

      【讨论】:

      • 很漂亮的把戏。有没有办法使用命名回调函数来做到这一点?
      • 定义回调函数,而不仅仅是将其名称作为字符串放入其中。
      • @hakre:我不明白。我知道你可以做preg_replace_callback("pattern","someFunction","subject"); 然后有一个单独的function someFunction ($matches) {...} 但例如你不能做preg_replace_callback("pattern","someFunction($someVar)","subject"); 我的问题是是否有办法做到这一点。好吧,这确实是OP的问题。我想我的问题是......您可以使用“use”将 var 传递给 anon 函数,如本答案所示。但是你可以做例如preg_replace_callback("pattern","someFunction" use ($someVar) ,"subject");
      • @CrayonViolent preg_replace_callback("pattern",function($m) use ($someVar) { call_some_other_function($someVar, $m); },"subject");,不,最初的问题是“我可以使用匹配作为数组的索引进行 preg_replace”
      • 是否有关于use 使用的文档可供我查看?我只是想看看这是我错过的地方
      【解决方案3】:

      您实际上可以将 preg_replace 与 /e 修饰符一起使用:

      preg_replace("/\{([a-zA-Z0-9_]+)\}/e", '$templateVariables[\'$1\']', $templateString)
      

      但这可能不是这里最安全的方式...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-05
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 2017-11-13
        相关资源
        最近更新 更多