【问题标题】:Use numeric literals with an array in PHP (preg_replace)在 PHP (preg_replace) 中将数字文字与数组一起使用
【发布时间】:2018-07-21 01:19:19
【问题描述】:

我正在尝试将数字文字与我的数组 $test 和 PHP 中的 preg_replace 一起使用,这就是我得到的:

$test["a"] = "hey";

// Find a as $0
echo preg_replace("/[a-z]/", "Found:$0", "a")."\n";

// Can replace it by "hey"
echo preg_replace("/[a-z]/", $test['a'], "a")."\n";

// Can't replace it :/
echo preg_replace("/[a-z]/", $test["$0"], "a")."\n";

如您所见,最后一个 preg_replace 函数不起作用,而另外两个函数工作正常...我尝试了很多次以各种技巧将 $0 包含在内,但仍然没有任何效果...您能帮帮我吗,好吗?

【问题讨论】:

    标签: php arrays preg-replace numeric literals


    【解决方案1】:

    您当前的用例不需要正则表达式,您可以(如果可能的话)使用strtrstr_replace,具体取决于要求:

    $test["a"] = "hey";
    $test["b"] = "you";
    
    echo strtr("a b", $test); //hey you
    
    echo str_replace(array_keys($test), array_values($test), "a b"); //hey you
    

    请参阅When to use strtr vs str_replace? 了解有什么区别。

    【讨论】:

      【解决方案2】:

      你可以使用preg_replace_callback()

      echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
          return $test[$b[0]];
      }, "a")."\n";
      

      更多测试:

      echo preg_replace_callback("/[a-z]/", function ($b) use ($test) {
          if (isset($b[0]) && isset($test[$b[0]]))
              return $test[$b[0]];
          return "";
      }, "a")."\n";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-29
        • 1970-01-01
        • 2011-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多