Application example of intercepting Chinese string with php mb_substr of function

  • 2021-07-10 18:58:23
  • OfStack

substr () function is used to intercept strings, but there will be problems for Chinese characters, while mb_substr () and mb_strcut can be used, which is similar to substr (), except that one more parameter should be added at the end of the function to set the encoding of strings. Using these two functions requires opening php_mbstring. dll in php. ini.


<?php 
header("content-type:text/html; charset=utf-8");
$string = " Hello, I'm good, everyone ";
echo strlen($string).'</br>';
echo mb_substr($string,0,4,'utf-8').'...</br>';
echo mb_strcut($string,0,4,'utf-8').'...';
?>

Output result:

21
Hello, I'm good...
You...

As can be seen from the above example, mb_substr divides characters by word, while mb_strcut divides characters by byte, but neither of them produces half a character.


Related articles: