代码之家  ›  专栏  ›  技术社区  ›  Paul Wicks asgeo1

在preg_replace_回调中指定回调函数?

  •  0
  • Paul Wicks asgeo1  · 技术社区  · 15 年前

    我有一些这样的代码(这是一个简化的示例):

    function callback_func($matches) {
      return $matches[0] . "some other stuff";
    }
    
    function other_func($text) {
      $out = "<li>"; 
      preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
      $out .= $desc ."</li> \r\n";
      return $out;
    }
    
    echo other_func("This is a _test");
    

    它的输出应该是

    <li>This is a _testsome other stuff</li>
    

    但我只是得到

    <li>This is a _test</li>
    

    我做错了什么/安抚PHP神灵需要什么奇怪的咒语?

    3 回复  |  直到 15 年前
        1
  •  5
  •   Ben Blank    15 年前

    preg_replace_callback 不就地修改字符串,而是返回其修改后的副本。请尝试以下说明:

    function other_func($text) {
        $out = "<li>"; 
        $out .= preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
        $out .= "</li> \r\n";
        return $out;
    }
    
        2
  •  0
  •   BraedenP    15 年前

    问题是,您永远不会将函数的输出追加到$out变量中。所以在回调函数中,必须使用:

    $out .= $matches[0] . "some other stuff";
    

    然后它会将结果添加到字符串中,供您输出。实际上,您只是返回一个值,而不使用它。

        3
  •  0
  •   Paul Wicks asgeo1    15 年前

    明白了。preg_replace_回调不会修改原始主题,我认为是这样的。我不得不改变

    preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);
    

    $desc = preg_replace_callback("/_[a-zA-Z]*/","callback_func",$desc);