Home > Backend Development > PHP Tutorial > The most accurate php function to intercept string length_php tips

The most accurate php function to intercept string length_php tips

WBOY
Release: 2016-05-16 20:05:47
Original
923 people have browsed it

It is said to be the most accurate interception length. In fact, I am not sure whether it is the most accurate. Just look at the effect below to know how accurate it is:
First, the string for testing:

<&#63;php 
header("Content-Type:text/html;charset=utf-8"); 
echo cn_substr_utf8('我是一个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('ai\'2145m a ch3我[是一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('【我,是一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('我是一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('我是,一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('我,是,一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('我是asd一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('【我i\'m[是一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('【i\'m a ch我[是一,个,和哈,哦也,,国家!',12); 
echo '<br />',cn_substr_utf8('【i\'2145m a ch3我[是一,个,和哈,哦也,,国家!',12); 
Copy after login

The following is the rendering of accurately intercepting the string:


The specific function code is as follows:

//utf-8中文截取,单字节截取模式 
function cn_substr_utf8($str,$length,$append='...',$start=0){ 
  if(strlen($str)<$start+1){ 
    return ''; 
  } 
  preg_match_all("/./su",$str,$ar); 
  $str2=''; 
  $tstr=''; 
  //www.phpernote.com 
  for($i=0;isset($ar[0][$i]);$i++){ 
    if(strlen($tstr)<$start){ 
      $tstr.=$ar[0][$i]; 
    }else{ 
      if(strlen($str2)<$length + strlen($ar[0][$i])){ 
        $str2.=$ar[0][$i]; 
      }else{ 
        break; 
      } 
    } 
  } 
  return $str==$str2&#63;$str2:$str2.$append; 
} 
Copy after login

If you think it is not accurate enough, you can make improvements or innovate on this basis. I hope this article about the PHP interception string length function will be helpful to your study.

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