如何用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
相关产品推荐
相关产品推荐

