Home  >  Article  >  Backend Development  >  PHP Chinese character interception to prevent garbled characters

PHP Chinese character interception to prevent garbled characters

PHP中文网
PHP中文网Original
2016-07-21 15:53:12959browse

When a Chinese character is truncated, according to the encoding rules, it always has to pull in other characters behind it and interpret them as Chinese characters. This is the reason why garbled characters appear. The combination of values ​​0x81 to 0xff and 0x00 is always displayed as "empty". According to this feature, adding a chr(0) after the substr result can prevent garbled characters.

Let's look at the code first
The code is as follows:

<?php        
$len = 15;           
$str = "这个新闻或是文章的标题很长,需要只显示前面一些字,后面用...来代替";        
echo strlen($str)<=$len ? $str : (substr($str,0,$len).chr(0)."...");      
?>


chr(0) related knowledge:
null means nothing, and the value of chr(0) is 0. Expressed in hexadecimal it is 0x00, expressed in binary it is 00000000
Although chr(0) will not display anything, it is a character.

ps:
If it is UTF-8, the Chinese characters in UTF-8 are 3 bytes. The intercepted length should be a multiple of 3 as much as possible to avoid the generation of garbled characters


http://www.bkjia.com/PHPjc/318755.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/318755.htmlTechArticle first look at the code copy The code is as follows: ?php $len=15; $str="The title of this news or article is very long. It is necessary to display only the first few words and replace them with..."; echostrlen($str)=$l. ..


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn