字符截取函数

if (!function_exists('mbsubstr')) {
/**
* 字符串截取,支持中文和其他编码
* @param string $str 需要转换的字符串
* @param int $start 开始位置
* @param int $length 截取长度
* @param string $encoding 编码格式
* @param string $suffix 截断显示字符
* @return false|mixed|string 返回结果
*/
function mbsubstr($str, $start = 0, $length = null, $encoding = "utf-8", $suffix = '...')
{
if (function_exists("mb_substr")) {
$slice = mb_substr($str, $start, $length, $encoding);
} elseif (function_exists('iconv_substr')) {
$slice = iconv_substr($str, $start, $length, $encoding);
if (false === $slice) {
$slice = '';
}
} else {
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$encoding], $str, $match);
$slice = join("", array_slice($match[0], $start, $length));
}
return $suffix ? $slice . $suffix : $slice;
}
}

if (!function_exists('sub_str')) {

/**
* 字符串截取
* @param string $str 需要截取的字符串
* @param int $start 开始位置
* @param int $length 截取长度
* @param bool $suffix 截断显示字符
* @param string $charset 编码格式
* @return string 返回结果
*/
function sub_str($str, $start = 0, $length = 10, $suffix = true, $charset = "utf-8")
{
if (function_exists("mb_substr")) {
$slice = mb_substr($str, $start, $length, $charset);
} elseif (function_exists('iconv_substr')) {
$slice = iconv_substr($str, $start, $length, $charset);
} else {
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("", array_slice($match[0], $start, $length));
}
$omit = mb_strlen($str) >= $length ? '...' : '';
return $suffix ? $slice . $omit : $slice;
}

}


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3