代码之家  ›  专栏  ›  技术社区  ›  dreeves

php的preg_replace,其中replace是匹配的任意函数

  •  0
  • dreeves  · 技术社区  · 15 年前

    假设我想将“foo”替换为“oof”:

    $s = "abc foo bar";
    echo preg_replace('/(foo)/', strrev("$1"), $s);
    

    而不是“ abc oof bar “我得到” abc 1$ bar “。 换句话说,它将文本字符串“$1”传递给strrev()函数,而不是regex match“foo”。

    在上面的代码中,解决这个问题的最佳方法是什么?

    1 回复  |  直到 15 年前
        1
  •  2
  •   kennytm    15 年前

    通过 /e 旗帜。

    echo preg_replace('/(foo)/e', 'strrev("\\1")', $s);
    

    更安全的选择是 preg_replace_callback .

    function revMatch ($matches) {
      return strrev($matches[1]);
    }
    ...
    
    echo preg_replace_callback('/(foo)/', "revMatch", $s);