修改正则表达式的反向引用(PHP)

时间:2010-09-23 14:14:33

标签: php regex preg-replace

沮丧......

所以,我想修改preg_replace的后向引用。想我实际上无法修改(?)所以我想知道是否可以改变正则表达式来实现相同的结果。

实施例。匹配[xx_xx]并输出"xx_xx""xx xx""xx_xx"很简单(如下所示)但是"xx xx"

$y = "this [fishing_rod] is bent";
echo preg_replace("/\[(.+?)\]/", "\"\\1\", $y);
// this fishing_rod is bent

我如何实现:这个钓鱼竿钓鱼竿弯曲?

(这只是一个例子,我正在做的事情更复杂!)

1 个答案:

答案 0 :(得分:1)

您需要使用preg_replace_callback功能

function fun($matches) {
        return str_replace('_',' ',$matches[1]); 
}

$y = "this [fishing_rod] is bent";
echo preg_replace_callback("/\[(.+?)\]/","fun", $y);