The most accurate PHP interception string length function, interception string_PHP tutorial

WBOY
Release: 2016-07-12 09:06:01
Original
883 people have browsed it

The most accurate php function to intercept string length, intercept string

It is said to be the most accurate interception length. In fact, I am not sure whether it is the most accurate. How specific is it? Just look at the effect below:
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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1066508.htmlTechArticleThe most accurate PHP function to intercept the string length. Intercepting the string is said to be the most accurate interception length. In fact, I don’t know. I’m sure it’s the most accurate. Just look at the effect below to see how accurate it is...
Related labels:
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