Home > php教程 > php手册 > 可以保证单词完整性的PHP英文字符串截取代码分享

可以保证单词完整性的PHP英文字符串截取代码分享

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:20:07
Original
1875 people have browsed it

这篇文章主要介绍了可以保证单词完整性的PHP英文字符串截取代码分享,代码中包含详细注释,需要的朋友可以参考下

直接上代码:

/** * 完整词的截取 * * @param $str * @param $start * @param $length * * @return string */ public static function usubstr($str, $start, $length = null) { // 先正常截取一遍. $res = substr($str, $start, $length); $strlen = strlen($str); /* 接着判断头尾各6字节是否完整(不残缺) */ // 如果参数start是正数 if ($start >= 0) { // 往前再截取大约6字节 $next_start = $start + $length; // 初始位置 $next_len = $next_start + 6 0 ? $start - 6 : 0; $prev_segm = substr($str, $prev_start, $start - $prev_start); } // start是负数 else { // 往前再截取大约6字节 $next_start = $strlen + $start + $length; // 初始位置 $next_len = $next_start + 6 0 ? $start - 6 : 0; $prev_segm = substr($str, $prev_start, $start - $prev_start); } // 判断前6字节是否符合utf8规则 if (preg_match('@^([x80-xBF]{0,5})[xC0-xFD]?@', $next_segm, $bytes)) { if (!empty($bytes[1])) { $bytes = $bytes[1]; $res .= $bytes; } } // 判断后6字节是否符合utf8规则 $ord0 = ord($res[0]); if (128 = $ord0) { // 往后截取 , 并加在res的前面. if (preg_match('@[xC0-xFD][x80-xBF]{0,5}$@', $prev_segm, $bytes)) { if (!empty($bytes[0])) { $bytes = $bytes[0]; $res = $bytes . $res; } } } if (strlen($res) ,

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template