2009-09-21 36 views
0

我有一些像这样的代码(这是一个简单的例子):在preg_replace_callback中指定回调函数?

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神,需要什么奇怪的咒语?

回答

5

preg_replace_callback不会修改字符串,而是返回修改后的副本。请尝试以下instread:

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

哎呀,应该刷新。在你做完之后就想出来了。不管怎么说,还是要谢谢你。 – 2009-09-21 22:48:47

0

问题是你永远不会将函数的输出附加到$ out变量中。因此,在callback_func(),你必须使用:

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

然后将结果添加到字符串为您输出。事实上,你只是返回一个价值,并且无所作为。

+0

你混合范围。 '$ out'在'other_func'中,但'$ matches'在'callback_func'中。 – 2009-09-21 22:42:02

0

想通了。 preg_replace_callback不会修改原来的主题,我认为它做了。我不得不改变

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

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