This article shares with you the most accurate php string length truncation function and the most precise string truncation function. you can make improvements on this basis, if you are interested, you can refer to it as the most precise clip length. In fact, I am not sure whether it is the most accurate. For more details, see the following results:
First test the string:
<? Php header ("Content-Type: text/html; charset = utf-8"); echo cn_substr_utf8 ('I Am A, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 ('AI \' 2145m a ch3 I [is a, a, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' [I, it's a, it's a, and ha, oh, it's also, country! ', 12); echo'
', Cn_substr_utf8 (' I Am A, A, and a, Oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' I am, one, one, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' I, yes, one, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' I'm asd 1, A, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' [I \'m [is a, A, and a, Oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' [I \'m a ch I [is a, a, and ha, oh, also, country! ', 12); echo'
', Cn_substr_utf8 (' [I \ '2145m a ch3 I [is a, a, and a, Oh, also, country! ', 12 );
The following describes how to precisely intercept a string:
The specific function code is as follows:
// UTF-8 Chinese truncation, single-byte truncation mode function cn_substr_utf8 ($ str, $ length, $ append = '... ', $ start = 0) {if (strlen ($ str) <$ start + 1) {return '';} preg_match_all ("/. /su ", $ str, $ ar); $ str2 =''; $ tstr = ''; // www.phpernote.com for ($ I = 0; isset ($ ar [0] [$ I]); $ I ++) {if (strlen ($ tstr) <$ start) {$ tstr. = $ ar [0] [$ I];} else {if (strlen ($ str2) <$ length + strlen ($ ar [0] [$ I]) {$ str2. = $ ar [0] [$ I];} else {break ;}} return $ str ==$ str2? $ Str2: $ str2. $ append ;}
If you think it is not accurate enough, you can make improvements or innovations on this basis. I hope this article on php's string length function truncation will be helpful for your learning.