使用preg_replace_callback和create_function

时间:2012-02-24 08:39:27

标签: php

我正在尝试使用preg_replace_callback替换句子中的单词。

"%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"

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

1 个答案:

答案 0 :(得分:2)

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

这应该有效(&gt; = PHP 5.3.0)

<?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将被导入其范围,并在调用时可用。如果你想进一步谷歌,这就是'关闭'超过$值的概念:)。

希望这有帮助。

相关问题