PHP intercepts the Utf-8 format string
In PHP, we often need to intercept strings. The English character occupies a byte, the Chinese character occupies two bytes, but the Chinese character occupies two bytes is relative to the GBK encoding but in the current internationally popular UTF8 encoding, a Chinese character occupies 3 bytes. This article introduces a function of PHP to intercept utf-8 format strings.
An example is provided:
function truncate_utf8_string ($string, $length, $etc = ' ... ') {
$result = ';
$string = Html_entity_decode (Trim (strip_tags ($string)), ent_quotes, ' UTF-8 ');
$strlen = strlen ($string);
for ($i = 0; (($i < $strlen) && ($length > 0)); $i + +) {
if ($number = Strpos (Str_pad (Decbin (Ord (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ') {
if ($length < 1.0) {break
;
}
$result. = substr ($string, $i, $number);
$length-= 1.0;
$i + + $number-1;
} else {
$result. = substr ($string, $i, 1);
$length-= 0.5;
}
}
$result = Htmlspecialchars ($result, ent_quotes, ' UTF-8 ');
if ($i < $strlen) {
$result. = $etc;
}
return $result;
}
If you need to intercept a string in utf-8 format, call this function directly.
<?php
$str = "If you need to intercept strings in utf-8 format, call this function directly." ";
Echo truncate_utf8_string ($STR, 10);//Output result: If you need to intercept utf-8 ...
? >
Thank you for reading, I hope to help you, thank you for your support for this site!