<?php
/*
@UTF-8编码的字符可能由1~3个字节组成。
*/
/*--------------------------方法一截取中文字符串方法------------------------------*/
function msubstr($str, $start, $len)
{
$tmpstr = "";
$strlen = $start + $len;
for ($i = 0; $i < $strlen; $i++) {
if (ord(substr($str, $i, 1)) > 0xa0) //ord()函数返回字符串的第一个字符的ASCII值
{
$tmpstr .= substr($str, $i, 2);
$i++;
} else {
$tmpstr .= substr($str, $i, 1);
}
}
return $tmpstr;
}
/*----------------------------第二种方法-----------------------------------*/
//截取的是UTF-8字符串
function utf_substr($str, $len)
{
$new_str = [];
for ($i = 0; $i < $len; $i++) {
$tem_str = substr($str, 0, 1);
if (ord($tem_str > 127)) {
$i++;
if ($i < $len) {
$new_str[] = substr($str, 0, 3);
$str = substr($str, 3);
}
} else {
$new_str[] = substr($str, 0, 1);
$str = substr($str, 1);
}
}
return join($new_str);//join()函数把数组元素组合为一个字符串
}
/*-------------------------------------第三种方法(UTF-8)--------------------------------*/
function cutstr($string, $length)
{
preg_match_all("/[-]|[�-遌|[€-縘|郲�-縘[€-縘|[�-颹[€-縘[€-縘|餥�-縘[€-縘[€-縘|[�-鱙[€-縘[€-縘[€-縘/", $string, $info);
$wordscut = "";
$j = 0;
for ($i = 0; $i < count($info[0]); $i++) {
$wordscut .= $info[0][$i];
$j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
if ($j > $length - 3) {
return $wordscut . "...";
}
}
return join('', $info[0]);
}
$string = "312哈哈,这个组合很难切割哦";
echo cutstr($string, 10);
/*---------------------------------下面是曾经用过的截取第三个的字符串的------------------------------*/
// $name1 = mysql_result($my_rst,0,"name");
// $name = preg_match("/([1-9][0-9]+)/",$name1,$r);
// $name = $r[0];
// if($name == ""){
// $name=preg_replace('#^(?:[-]|[�-
|