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

含\x14控制字符的PHP字符串json_decode失效问题求解

解决包含\x14控制字符的JSON解析问题

问题根源

\x14是ASCII控制字符(对应十进制20的设备控制符),而JSON规范明确禁止字符串中出现未转义的ASCII控制字符(仅允许\t、\n、\r、\f、\b这几个转义后的控制字符),所以json_decode遇到这类字符会直接返回null。

你可以通过以下代码验证错误类型:

$string = '[{"name":"hello", "weird":"\x14"}]';
$json= json_decode($string, true);
echo json_last_error_msg(); // 输出 "Control character error, possibly incorrectly encoded"

解决方案

根据需求选择对应的处理方式:

1. 移除控制字符(无需保留该字符时)

用正则过滤掉所有非允许的ASCII控制字符:

$string = '[{"name":"hello", "weird":"\x14"}]';
// 过滤\x00-\x08、\x0B、\x0C、\x0E-\x1F范围内的控制字符
$cleanedString = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string);
$json = json_decode($cleanedString, true);
print_r($json);
// 输出:Array ( [0] => Array ( [name] => hello [weird] => ) )

2. 转义控制字符(需要保留该字符时)

把原始控制字符转成JSON兼容的Unicode转义格式\u0014:

$string = '[{"name":"hello", "weird":"\x14"}]';
// 将\x14替换为JSON允许的\u0014
$fixedString = str_replace("\x14", "\\u0014", $string);
$json = json_decode($fixedString, true);
print_r($json);
// 输出:Array ( [0] => Array ( [name] => hello [weird] =>  ) )
// 注:输出的方框是\x14的可视化表现,实际字符已被正确解析

如果字符串包含多种控制字符,可使用批量转义函数:

function escapeJsonControlChars($str) {
    return preg_replace_callback('/[\x00-\x1F]/', function($match) {
        return sprintf('\\u%04x', ord($match[0]));
    }, $str);
}

$string = '[{"name":"hello", "weird":"\x14"}]';
$fixedString = escapeJsonControlChars($string);
$json = json_decode($fixedString, true);
print_r($json);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:01:07