如何在php上解码字符串 iconv解码不起作用

问题描述

请求 http://a.com/?q=\xC3\xA2\xB0\xED

来源

$str1 = "\xC3\xA2\xB0\xED";
$str2 = '\xC3\xA2\xB0\xED';
$str3 = $_GET['q'];

echo "string1 : " . mb_detect_encoding($str1) . "<br>";
echo iconv("CP949","UTF-8",$str1) . "<br>";
echo "string2 : " . mb_detect_encoding($str2) . "<br>";
echo iconv("CP949",$str2) . "<br>";
echo "string3 : " . mb_detect_encoding($str3) . "<br>";
echo iconv("CP949",$str3) . "<br>";

回复

string1 : UTF-8
창고
string2 : ASCII
\xC3\xA2\xB0\xED
string3 : ASCII
\xC3\xA2\xB0\xED

$str2,$str3 解码失败.. 我该如何解决? 以及为什么不同.. 单引号字符串 VS 双引号字符串

版本:PHP 7.1.30

提前致谢

解决方法

当您对字符串使用单引号时,每个字符都是原样,php 不会解释它,因此 $str2 无法转换为另一种编码。

查询字符串也假定为单引号字符串,所以 $str3 就像 $str2。

解决方案是stripcslashes。它实际上将单引号字符串转换为双引号字符串。

你可以通过这种方式修复它:

$str2 = '\xC3\xA2\xB0\xED';
$str2 = stripcslashes($str2);
$str3 = $_REQUEST["q"];
$str3 = stripcslashes($str3);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...