解决中文搜索乱码实现方式

      发布在:后端技术      评论:0 条评论

解决中文搜索乱码实现方式摘抄自shopxo框架的实现方式,中文乱码主要是在url传入中文后台接收显示成乱码。

cs

具体查看到shopxo框架实现的解决方法:


/**
* 字符串转ascii
* @author   Devil
* @blog     http://gong.gg/
* @version  1.0.0
* @datetime 2019-06-02T01:13:47+0800
* @param    [string]          $str [字符串]
* @return   [string]               [转换后的ascii]
*/
function StrToAscii($str)
{
$change_after = '';
if(!empty($str))
{
// 编码处理
       $encode = mb_detect_encoding($str);
if($encode != 'UTF-8')
{
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}

// 开始转换
       for($i=0; $i<strlen($str); $i++)
{
$temp_str = dechex(ord($str[$i]));
if(isset($temp_str[1]))
{
$change_after .= $temp_str[1];
}
if(isset($temp_str[0]))
{
$change_after .= $temp_str[0];
}
}
}
return strtoupper($change_after);
}


/**
* ascii转字符串
* @author   Devil
* @blog     http://gong.gg/
* @version  1.0.0
* @datetime 2019-06-02T01:14:04+0800
* @param    [string]       $ascii [ascii]
* @return   [string]              [转换后的字符串]
*/
function AsciiToStr($ascii)
{
$str = '';
if(!empty($ascii))
{
// 开始转换
       $asc_arr = str_split(strtolower($ascii), 2);
for($i=0; $i<count($asc_arr); $i++)
{
$str .= chr(hexdec($asc_arr[$i][1].$asc_arr[$i][0]));
}

// 编码处理
       $encode = mb_detect_encoding($str);
if($encode != 'UTF-8')
{
$str = mb_convert_encoding($str, 'UTF-8', $encode);
}
}
return $str;
}

在接收上的处理方式

// 搜索关键字  这里只处理的是url传参接收方式,应该是ajax不存在这问题吧
$this->params['wd'] = empty($this->params['wd']) ? '' : (IS_AJAX ? trim($this->params['wd']) : AsciiToStr($this->params['wd']));

生成的url中,把中文转成ascii传入

MyUrl('index/search/index', ['wd'=>StrToAscii($keywords)])

最后效果截图

未标题-1

相关文章
热门推荐