【问题标题】:PHP: preg_replace_callback changes the order of the resultPHP:preg_replace_callback 改变结果的顺序
【发布时间】:2012-07-16 00:13:24
【问题描述】:

我有以下代码

return preg_replace_callback(
    "#\{gallery: '(.+?)'(?: dir: ([0-1]))?\}#i",
    create_function('$i', 'echo $i[1];' ),
    $string);

我的问题是,如果我的字符串看起来像这样:

top
{gallery: 'images/'}
center
{gallery: 'images/characters'}
bottom

当它被渲染时,它看起来像这样:

images/
images/characters
top center bottom

为什么要更改顺序并将替换的代码放在顶部,而将其他所有内容放在底部,甚至是中间的东西?

【问题讨论】:

  • 不应该将此问题标记为regex 而不是nsregularexpression 吗?
  • 回调函数中不要echo,而是return

标签: php regex preg-replace-callback


【解决方案1】:

您应该在替换回调中使用return 语句:

$string = "top {gallery: 'images/'} center {gallery: 'images/characters'} bottom";
$string = preg_replace_callback(
  "#\{gallery: '(.+?)'(?: dir: ([0-1]))?\}#i", 
  create_function('$i', 'return $i[1];'), 
  $string
);
echo $string . PHP_EOL;

// Outputs: top images/ center images/characters bottom

【讨论】:

  • 现在是 2012 年。PHP 现在有 anonymous functions
  • @Phil:我的服务器在 5.2 上运行:/
  • @WaldirBolanos 你总是在你的服务器上运行六年前的软件吗?
  • 没有 Phil,它是客户端服务器(在 godaddy.com 上)我无能为力,
  • 请注意,此 (create_function()) 在 PHP 7.2 及更高版本中已弃用。对于 PHP 7.2 之前的所有版本,它将执行 eval(),它与 ​​eval() 具有相同的安全问题。它的性能也很差,内存使用量很大。
猜你喜欢
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 2017-11-18
  • 2017-08-03
相关资源
最近更新 更多