You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中preg_replace弃用问题:如何改用preg_replace_callback改写代码?

Fixing Deprecated preg_replace with preg_replace_callback

No sweat, let's get this sorted out. The core issue here is that certain usage patterns for preg_replace are now deprecated in modern PHP, so switching to preg_replace_callback is the recommended fix.

First, let's recap what your original code does: it strips out s= or sessionhash= parameters (and their 32-character alphanumeric values) from a query string, along with any trailing escaped ampersands, while preserving the preceding non-alphanumeric character.

Here's how to rewrite it using preg_replace_callback:

// Replace the deprecated preg_replace call with preg_replace_callback
$query_string = preg_replace_callback(
    '/([^a-z0-9])(s|sessionhash)=[a-z0-9]{32}(&|&)?/',
    function($matches) {
        // This returns the first captured group, exactly like '\1' did in your original code
        return $matches[1];
    },
    $match[2]
);

// The rest of your code stays exactly the same
$foruminfo['link'] = $match[1] . '?' . $vbulletin->session->vars['sessionurl_js'] . substr($query_string, 1);

What's changed?

  • Instead of using a replacement string with \1, we pass an anonymous function that receives the $matches array (which holds all captured groups from the regex).
  • $matches[1] maps directly to the first captured group ([^a-z0-9]) from your original regex, so returning it gives identical behavior to your original '\1' replacement.
  • The regex pattern itself doesn't need any tweaks—we're just swapping how we handle the replacement logic to align with PHP's modern standards.

This approach eliminates the deprecation warning while keeping your original functionality intact.

内容的提问来源于stack exchange,提问作者Zain Azeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:01:58