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

如何用PHP提取MySQL错误信息中引号内列名并格式化?

PHP Solution to Extract and Format Quoted Column Name from MySQL Error

Here's the most concise PHP solution to pull the quoted column name from your MySQL error message and format it into the clean "Sam Office Balance" style:

$error = "Data truncated for column 'sam_office_balance' at row 1";
// Capture the text inside single quotes
preg_match("/'([^']+)'/", $error, $matches);
// Replace underscores with spaces and capitalize each word
$formatted = ucwords(str_replace('_', ' ', $matches[1]));

echo $formatted; // Output: Sam Office Balance

Breakdown of the code:

  • Regex capture: preg_match("/'([^']+)'/", $error, $matches) targets exactly the text between single quotes, storing the column name in $matches[1].
  • Space replacement: str_replace('_', ' ', $matches[1]) swaps underscores for spaces to make the text natural to read.
  • Title case formatting: ucwords() capitalizes the first letter of each word, giving you the polished format you need.

Optional: Add error resilience

If you want to handle edge cases where the error message might not follow the expected format (no quoted text), wrap the logic in a conditional to avoid undefined index warnings:

$error = "Data truncated for column 'sam_office_balance' at row 1";
$formatted = '';

if (preg_match("/'([^']+)'/", $error, $matches)) {
    $formatted = ucwords(str_replace('_', ' ', $matches[1]));
}

echo $formatted; // Outputs the formatted string or empty if no match is found

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:50:44