Summary of php Chinese String Interception Method Example

  • 2021-07-21 07:34:29
  • OfStack

This paper summarizes the php Chinese string interception method, which is a very practical skill. Share it for your reference. Specific methods are analyzed as follows:

Intercepting Chinese characters with PHP function substr may cause garbled codes, mainly because substr may abruptly "saw" a Chinese character into two halves.

The solution is as follows:

1. mb_substr interception using mbstring extension library will not appear garbled.

2. Write the interception function by yourself, but the efficiency is not as high as that of mbstring extension library.

3. If you are only outputting intercepted strings, you can do this as follows: substr ($str, 0, 30). chr (0).

substr () function can divide text, but if the text to be divided includes Chinese characters, it often encounters problems. At this time, you can use the function mb_substr () /mb_strcut. The usage of mb_substr () /mb_strcut is similar to substr (), except that one more parameter should be added at the end of mb_substr ()/mb_strcut to set the encoding of the string. However, the same server does not open php_mbstring. dll, which needs to be opened in php. mbstring.

Give two examples:

① Example of mb_substr


<?php
echo mb_substr(' In this way 1 Come on, my string won't be garbled ^_^', 0, 7, 'utf-8');
// Output: This 1 Come to my words 
?>

② Example of mb_strcut


<?php
echo mb_strcut(' In this way 1 Come on, my string won't be garbled ^_^', 0, 7, 'utf-8');
// Output: This 1
?>

From the above example, it can be seen that mb_substr splits characters by word, while mb_strcut splits characters by byte, but neither of them produces half a character phenomenon.

PHP Realization of Chinese Character String Interception without Garbled Code Method;


<?php
// This function completes the string fetching with Chinese characters 
function substr_CN($str,$mylen){ 
$len=strlen($str);
$content='';
$count=0;
for($i=0;$i<$len;$i++){
if(ord(substr($str,$i,1))>127){
$content.=substr($str,$i,2);
$i++; 
}else{
$content.=substr($str,$i,1);
}
if(++$count==$mylen){
break;
}
}
echo $content;
}

$str="34 People's Republic of China 56";
substr_CN($str,3);// Output 34 Medium 
?>

I hope this article is helpful to everyone's PHP programming.


Related articles: