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

PHP5.6升级至7.2遇未定义常量警告,求正确正则匹配方案

Fixing "Undefined Constant" Warnings When Upgrading PHP 5.6 to 7.2

I’ve been in your shoes before—upgrading PHP versions and dealing with those pesky undefined constant warnings from unquoted array keys. Your current regex is on the right track, but it’s matching too broadly. Let’s refine it to target exactly what you need:

The Correct Regex Pattern

Use this regex to find only the unquoted array keys attached to variables, while skipping standalone brackets and pure numeric indices:

Find:

(\$[a-zA-Z0-9_]+)\[(?!\d+\])([a-zA-Z0-9_\-\s]+)\]

Replace with:

$1['$2']

Breakdown of the Regex

Let’s break down why this works:

  • (\$[a-zA-Z0-9_]+): Captures the variable name (starts with $, followed by valid PHP variable characters: letters, numbers, underscores). This ensures we only target array access attached to variables, not standalone [test] strings.
  • \[: Matches the opening bracket of the array index.
  • (?!\d+\]): A negative lookahead that skips any index that’s purely numeric (like [1] or [123]). These numeric indices don’t need quotes in PHP, so we leave them as-is.
  • ([a-zA-Z0-9_\-\s]+): Captures the actual index name, allowing letters, numbers, underscores, hyphens, and spaces (matching your original use case).
  • \]: Matches the closing bracket.

Examples of What It Does

Matches (and replaces):

  • $user[name] → $user['name']
  • $product[1_item] → $product['1_item']
  • $settings[api-key] → $settings['api-key']
  • $data[ test value ] → $data[' test value ']

Doesn’t Match (leaves as-is):

  • Standalone [test] (no variable prefix)
  • $var[123] (pure numeric index)
  • $item[456]

Tips for Usage

  1. Test first: Run this regex on a copy of your codebase before applying it to production—double-check for any edge cases (like variable names with unusual patterns, though PHP’s variable naming rules make this unlikely).
  2. IDE Support: Most modern IDEs (VS Code, PhpStorm, Sublime Text) support lookaheads in their find/replace tools, so this should work seamlessly.
  3. Edge Cases: If you have indices with other special characters (though your original regex didn’t include them), you can adjust the character class [a-zA-Z0-9_\-\s]+ to add them (e.g., add . if you have indices like [user.name]).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:00:02