preg_replace 更新到 PHP 5.4 后无法使用

preg_replace not working after updating to PHP 5.4

我在使用 preg_replace() 时遇到问题,我相信在将我的主机 PHP 版本从 5.3 更新到 5.4 之后。

代码之前运行良好,但现在出现问题:

function update_comments($comments)
{
  if (!empty($comments) && is_array($comments)) {
    foreach ($comments as &$comment)
      update_comment(&$comment);
  }

  return $comments;
}

function update_comment($comment) {
$repl = '<a href="#">[=12=]</a>';
$comment['comment'] = preg_replace('~#(\d+)~', $repl, $comment['comment']);
return $comment;
}

谁能帮帮我?

阿比德,欢迎使用 Whosebug!

您能否添加当前输出和预期输出以及您的错误消息?因为我看到您使用了在 5.4 中删除的 call time pass-by-reference。 (update_comment(&$comment))。

我尝试 运行 代码并采用了它,我发现它在更改后似乎工作正常。这是一个 声明式 命令式 方式的例子。

function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        foreach ($comments as $idx => $comment) {
            $comments[$idx] = update_comment($comment);
        }
    }

    return $comments;
}

此处作为声明示例

function update_comments($comments)
{
    if (!empty($comments) && is_array($comments)) {
        $comments = array_map(function ($comment) {
            return update_comment($comment);
        }, $comments);
    }

    return $comments;
}

这是我如何使用您的代码的示例。您还可以在这里修改特定的 PHP 版本:http://sandbox.onlinephpfunctions.com/code/10e616237c0c75c8e3520bdf5866040231879cde

$comments = update_comments([
    ['comment' => 'This is my #1 comment.'],
    ['comment' => 'This is my #2 comment.']
]);

print_r($comments);

// Array
// (
//     [0] => Array (
//             [comment] => This is my <a href="#">#1</a> comment.
//         )
// 
//     [1] => Array (
//             [comment] => This is my <a href="#">#2</a> comment.
//         )
// 
// )

让我知道这是否有帮助,或者您的 preg_replace() 问题是否仍然存在。