dounai9294 2013-04-30 09:53
浏览 54

PHP mb_strpos空响应,中文

I try to find a space in a string using the mb_* functions. It works for latin chars but not Chinese... I have tried to utf8_encode and iconv to utf-8 since other threads have suggested that this might be the problem.

Function that gives error is mb_strpos that returns nothing for Chinese, but a valid int for English and other latin char based texts.

I am not all that strong in encoding but assume that different encoding is causing this problem. So I am most of all asking for help on where to search since it seems that there is nothing wrong with the php-functions.

This works for both English and Chinese until mb_strpos:

// TEST THAT DID NOT WORK
//$text=iconv('ISO-8859-1','utf-8',$text);//that's NOT a solution!
//$text=utf8_encode($text);//that's NOT a solution!

// Set vars
$len = 150;


// Next to code lines are OK for both English AND Chinese
// get substring based on $len, then get length of string. Both in multibyte
$text_cropped = mb_substr($text,0,$len,'UTF-8'); // works for English AND Chinese
$string_cropped_length = mb_strlen ($text_cropped,'UTF-8');

// mb_strpos only works for English, but not for Chinese
//find last space within length in multibyte
$last_space = mb_strpos ( $text , ' ', $string_cropped_length, 'UTF-8');

// Hack to only use $last_space if mb_strpos did work
// there is an error in mb_strpos based on php version. It may return empty for chinese chars

// a work around until php upgrade is test for value of last_spave and do an if-else
if(intval($last_space) > 0) {
    $text_cropped_final = mb_substr($text,0,$last_space,'UTF-8');
} else {
    $text_cropped_final = $text_cropped;
}

return $text_cropped_final . '...';
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab(相关搜索:紧聚焦)
    • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
    • ¥15 路易威登官网 里边的参数逆向
    • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
    • ¥50 需求一个up主付费课程
    • ¥20 模型在y分布之外的数据上预测能力不好如何解决
    • ¥15 processing提取音乐节奏
    • ¥15 gg加速器加速游戏时,提示不是x86架构
    • ¥15 python按要求编写程序
    • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入