【php基础】iconv 与 mb_convert_string 字符串转换

最近也一直在和字符串转换打交道,比较常用到的就是这两个php自带的字符串转换.那么接下来我会以一些场景来使用这两个字符串编码转换函数


使用场景:
请求:ajax POST请求
服务器编码 GBK
页面编码 GBK

问题:因为ajax请求发出的数据都是utf-8格式的编码,因此我们必须要将utf-8编码的数据进行一个转换

解决办法1: 使用iconv

<?php
$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取
$inCharset = "UTF-8";
$outCharset = "GBK";
$postStr = iconv($inCharset,$outCharset,$postStr);
// 将字符串转换为$_POST形式的数组
parse_str($postStr,$_post);

解决办法2: 使用mb_convert_encode()

<?php
$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取
$inCharset = "UTF-8";
$outCharset = "GBK";
$postStr = mb_convert_encode($postStr,$outCharset,$inCharset);

// 将字符串转换为$_POST形式的数组
parse_str($postStr,$_post);

以上两种方法均可以进行字符串转码,然而有一点需要注意,如果将转换好的字符串转回去,切不可两种方法混用.否则中文字符可能会出现阶段的问题。

示例:

<?php
$postStr = file_get_contents("file://input"); // 将post的数据以字符流的形式读取
$inCharset = "UTF-8";
$outCharset = "GBK";
$postStr = mb_convert_encode($postStr,$outCharset,$inCharset);

// 转换为原来的字符串
$postStr = iconv($outCharset,$inCharset."//IGNORE",$postStr);
// 如果源 $postStr为 UTF-8'我是谁?'
// 那么新的 $postStr'?' ,如果不加 "//IGNORE" 结尾 则会跑出一个异常

因此千万不要嵌套两个方法进行相互转换。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值