////////////////////////////////////////////////////////////////////
PHP intercepts string functions mixed in English and punctuation (never garbled)
This procedure is tested and passed in Utf-8 and gb2312. The user tests the Big5 itself.
function left (source string, intercept the specified number of strings, encode (can be omitted, default is Utf-8))
////////////////////////////////////////////////////////////////////
function left ($str, $len, $charset = "Utf-8")
{
If the intercept length is less than or equal to 0, the null is returned
if (!is_numeric ($len) or $len <= 0)
{
Return "";
}
If the intercept length is greater than the total string length, the current string is returned directly
$sLen = strlen ($STR);
if ($len >= $sLen)
{
return $str;
}
Determine what encoding to use, default is Utf-8
if (Strtolower ($charset) = = "Utf-8")
{
$len _step = 3; If it is utf-8 encoded, the Chinese character length is 3
}else{
$len _step = 2; If it is gb2312 or BIG5 encoded, the Chinese character length is 2
}
Performing interception operations
$len _i = 0;
Initializes the count of the number of strings currently intercepted, which is the number of strings (non-bytes)
$substr _len = 0; Initialize the total number of bytes that should be intercepted
for ($i =0; $i < $sLen; $i + +)
{
if ($len _i >= $len) break; Stop looping after always intercepting $len strings
Determines, if the string is Chinese, the current total number of bytes plus the length of the corresponding encoded medium character
if (Ord (substr ($str, $i, 1)) > 0xa0)
{
$i + = $len _step-1;
$substr _len + = $len _step;
}else{//Otherwise, for English characters, add 1 bytes
$substr _len + +;
}
$len _i + +;
}
$result _str = substr ($str, 0, $substr _len);
return $result _str;
}
////////////////////////////////////////////////////////////////////
Invoke Example
////////////////////////////////////////////////////////////////////
$STR = "Space is also counted as a character";
echo "truncated string:". Left ($str, 14);
?>
PHP captures mixed characters in English and Chinese