Home > Backend Development > PHP Tutorial > About php interception string length function

About php interception string length function

墨辰丷
Release: 2023-03-30 08:40:01
Original
1017 people have browsed it

This article mainly introduces the PHP interception string length function. Interested friends can refer to it. I hope it will be helpful to everyone.

First enter the string for testing:

<?php 
header("Content-Type:text/html;charset=utf-8"); 
echo cn_substr_utf8(&#39;我是一个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;ai\&#39;2145m a ch3我[是一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;【我,是一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;我是一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;我是,一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;我,是,一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;我是asd一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;【我i\&#39;m[是一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;【i\&#39;m a ch我[是一,个,和哈,哦也,,国家!&#39;,12); 
echo &#39;<br />&#39;,cn_substr_utf8(&#39;【i\&#39;2145m a ch3我[是一,个,和哈,哦也,,国家!&#39;,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=&#39;...&#39;,$start=0){ 
  if(strlen($str)<$start+1){ 
    return &#39;&#39;; 
  } 
  preg_match_all("/./su",$str,$ar); 
  $str2=&#39;&#39;; 
  $tstr=&#39;&#39;; 
  //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?$str2:$str2.$append; 
}
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of methods and examples of PHP file upload class

Methods and examples of PHP implementation of paging class

How to generate QR code with logo in php

The above is the detailed content of About php interception string length 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