2012-02-24 44 views
0

我想用preg_replace_callback替换句子中的单词。使用preg_replace_callback和create_function

"%1% and %2% went up the %3%"

应该成为

"Jack and Jill went up the hill"

我已经下面给出我的代码。

<?php 
    $values = array("Jack", "Jill", "hill"); 
    $line = "%1% and %2% went up the %3%"; 
    $line = preg_replace_callback(
    '/%(.*?)%/', 
    create_function(
     // single quotes are essential here, 
     // or alternative escape all $ as \$ 
     '$matches', 
     'return $values[$matches[1]-1];' 
    ), 
    $line 
); 
    echo $line; 
?> 

我所得到的是

" and went up the "

如果我给return $matches[1]-1;,我越来越

"0 and 1 went up the 2"

它是一个范围的问题吗?如何使这个工作? 任何帮助,将不胜感激。

回答

2

这确实是一个范围界定问题 - 由create_function创建的匿名函数无权访问$values

这应该工作(> = 5.3.0 PHP)

<?php 
    $values = array("Jack", "Jill", "hill"); 
    $line = "%1% and %2% went up the %3%"; 
    // Define our callback here and import $values into its scope ... 
    $callback = 
    function ($matches) use ($values) 
    { 
     return $values[$matches[1]-1]; 
    }; 

    $line = preg_replace_callback(
    '/%(.*?)%/', 
    $callback, // Use it here. 
    $line 
); 
    echo $line; 
?> 

通过声明use ($values)回调函数,$values将导入其范围和可用时,它的调用。如果你想进一步Google的话,这就是'价值'超过$价值的概念。

希望这会有所帮助。