Home > Backend Development > PHP Tutorial > Example tutorial of PHP Chinese interception string function

Example tutorial of PHP Chinese interception string function

零下一度
Release: 2023-03-10 19:22:01
Original
1410 people have browsed it

本节内容:
php中文截取字符窜函数

例子:

<?php
/**
* 中文
字符串截取
函数
* by www.jbxue.com
*/
function cut_str($string,$sublen,$filter=true,$start=0,$code=&#39;UTF-8&#39;){
 if($filter) $string=Html2Text($string);
 if($code==&#39;UTF-8&#39;){
   $pa="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  preg_match_all($pa,$string,$t_string);
  if(count($t_string[0])-$start>$sublen) return join(&#39;&#39;,array_slice($t_string[0],$start,$sublen))."...";
  return join(&#39;&#39;,array_slice($t_string[0],$start,$sublen));
 }else{
  $start=$start*2;
  $sublen=$sublen*2;
  $strlen=strlen($string);
  $tmpstr=&#39;&#39;;
  for($i=0;$i<$strlen;$i++){
   if($i>=$start&&$i<($start+$sublen)){
    if(ord(substr($string,$i,1))>129){
     $tmpstr.=substr($string,$i,2);
    }else{
     $tmpstr.=substr($string,$i,1);
    }
   }
   if(ord(substr($string,$i,1))>129) $i++;
  }
  if(strlen($tmpstr)<$strlen ) $tmpstr.="...";
  return $tmpstr;
 }
}
//html转换函数
function Html2Text($str){
 $str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU","",$str);
 $alltext = "";
 $start = 1;
 for($i=0;$i<strlen($str);$i++){
  if($start==0 && $str[$i]==">"){
   $start = 1;
  }else if($start==1){
   if($str[$i]=="<"){
    $start = 0;
    $alltext .= " ";
   }else if(ord($str[$i])>31){
    $alltext .= $str[$i];
   }
  }
 }
 $alltext = str_replace(" "," ",$alltext);
 $alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
 $alltext = preg_replace("/[ ]+/s"," ",$alltext);
  return $alltext;
}
Copy after login

The above is the detailed content of Example tutorial of PHP Chinese interception string function. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template