本文共 1533 字,大约阅读时间需要 5 分钟。
= 32 && $t <= 126)) { $tn = 1; $n++; $noc++; } elseif (194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noc += 2; } elseif (224 <= $t && $t <= 239) { $tn = 3; $n += 3; $noc += 2; } elseif (240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noc += 2; } elseif (248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noc += 2; } elseif ($t == 252 || $t == 253) { $tn = 6; $n += 6; $noc += 2; } else { $n++; } if ($noc >= $length) { break; } } if ($noc >= $length) { $n -= $tn; } $strcut = substr($string, 0, $n); $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '', '·', '…'), array(' ', '&', '"', "'", '“', '”', '—', '', '·', '…'), $strcut); } else { $dotlen = strlen($dot); $maxi = $length - $dotlen - 1; $current_str = ''; $search_arr = array('&', ' ', '"', "'", '“', '”', '—', '', '·', '…', '∵'); $replace_arr = array('&', ' ', '"', "'", '“', '”', '—', '', '·', '…', ' '); $search_flip = array_flip($search_arr); for ($i = 0; $i < $maxi; $i++) { $current_str = ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i]; if (in_array($current_str, $search_arr)) { $key = $search_flip[$current_str]; $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str); } $strcut .= $current_str; } } return $strcut . $dot; } ``` 这段代码实现了以下功能: 1. **字符串长度判断**:如果原始字符串长度小于等于所需截取长度,直接返回原字符串。 2. **字符替换**:将一些特殊字符替换为易于显示的格式,确保截取后的字符串显示正确。 3. **字符编码处理**:根据字符编码类型(UTF-8或GBK)调整截取逻辑,确保正确处理Multi-byte 字符。 4. **断言点处理**:智能计算断言点的位置,避免断言点在中间导致信息丢失。 5. **文本优化**:在截取后,恢复原始字符格式,确保输出格式一致。 该函数适用于需要对文本内容进行精确截取的场景,能够处理多种编码格式,并确保截取后的字符串格式完整。转载地址:http://uvtfk.baihongyu.com/