Using PHP's substr() with special characters at the end results in question marks

三世轮回 提交于 2019-12-04 15:59:56

问题


When I use the substr() function in PHP, I get an question mark (a square with a question mark - depending on the browser) at the end of the string when this last character was a special one, like ë or ö, etc...

$introtext = html_entity_decode($item->description, ENT_QUOTES, "UTF-8");
$introtext = substr($introtext, 0, 200);

How can I escape this?


回答1:


If your string has multibyte encoding (like UTF-8) does, you should use mb_substr to avoid problems like this:

$introtext=mb_substr($introtext,0,200);



回答2:


That is because substr does not work with multibyte characters. substr will probably cut a multibyte character "in half". You should instead use mb_substr. Also make sure that your file is saved in UTF-8.

$introtext = mb_substr($introtext, 0, 200);



回答3:


In case someone tried the previous answers, and it still didn't work:

Try to add a Unicode name in mb_substr like:

$introtext = mb_substr($introtext, 0, 200, 'utf-8');



回答4:


Use mb_substr



来源:https://stackoverflow.com/questions/6257818/using-phps-substr-with-special-characters-at-the-end-results-in-question-mark

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!