Home > php教程 > php手册 > 最准确的php截取字符串长度函数,截取字符串

最准确的php截取字符串长度函数,截取字符串

WBOY
Release: 2016-06-13 08:52:18
Original
1034 people have browsed it

最准确的php截取字符串长度函数,截取字符串

说是最精确截取长度,其实我也不敢确定是否是最精确的,具体有多精确看下面的效果就知道了:
先上测试用的字符串:

<&#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

下面是精确截取字符串的效果图:


具体函数代码如下:

//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

如果大家认为还不够准确大家可以在此基础上进行改进,或者是创新,希望这篇关于php截取字符串长度函数的文章对大家的学习有所帮助。

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