Skip to content

Instantly share code, notes, and snippets.

@wgm89
Created November 6, 2013 06:02
Show Gist options
  • Select an option

  • Save wgm89/7331642 to your computer and use it in GitHub Desktop.

Select an option

Save wgm89/7331642 to your computer and use it in GitHub Desktop.
substr
function sub_str($str,$start=0,$length=60,$left="...",$charset="utf-8")
{
if($charset=="utf-8"){
$index=0;
$index1=0;
$result="";
$haslen=0;
for($i=0;$i<$length;$i++)
{
$index1=$index;
$len=0;
$len1=0;
$first_b=substr($str,$index,1);
if(ord($first_b)>224){
if($i>=$start){
$len=3;
$len1=3;
}
$index+=$len;
$haslen+=$len;
}elseif(ord($first_b)>192){
if($i>=$start) {
$len=2;
$len1=2;
}
$index+=$len;
$haslen+=$len;
}else{
if($i>=$start) {
$len=1;
$len1=1.5;
}
$index+=$len;
$haslen+=$len1;
}
if($haslen<=$length){
$result.=substr($str,$index1,$len);
}else{
break;
}
}
}else{
$result=mb_substr($str,$start,$length,$charset);
}
if($result!=$str){
$result.=$left;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment