search
HomeBackend DevelopmentPHP TutorialPHP中英文混合排版中处理字符串常用的函数


  /*
  我们在处理中文数据时,经常要处理一些情况,下面就是针对
  这些情况,我做的一些函数,已经用在了实践中
  
  */
  
  # 判断某个位置是中文字符的左还是右半部分,或不是中文
  # 返回值 -1 左 0 不是中文字符 1 右
  # 用法
  /*
  $a = 'this is 中文';
  print is_chinese($a, 1); // 0
  print is_chinese($a,8); // -1
  print is_chinese($a,9); // 1
  */
  function is_chinese(&$str, $location) {
  $ch = true;
  $i = $location;
  while(ord($str[$i])>0xa0 && $i >= 0) {
  $ch = !$ch;
  $i --;
  }
  
  if($i != $location) {
  $f_str = $ch ? 1: -1;
  }
  else {
  $f_str = false;
  }
  
  return $f_str;
  }
  
  # 中文字符串倒置函数
  # 如果一个将一个有中文的字符串用strrev倒过来,就会产生乱码
  /*
  print cstrrev('this is 中文'); // 文中 si siht
  */
  
  function cstrrev(&$str) {
  $long = strlen($str);
  for($f_str=', $chinese=false, $i=$long-1; $i>=0; $i--) {
  if(ord($str[$i]) > 0xa0) {
  $chinese = ! $chinese;
  if($chinese == false) {
  $f_str .= $str[$i].$str[$i+1];
  }
  }
  else {
  $f_str .= $str[$i];
  }
  }
  return $f_str;
  }
  /* 中文字符串截取函数
  一些中文字符串截取函数经常有一些问题,例如在一些自动换行程序中
  $a=“1中2”;
  经两次截取后,
  csubstr($str,$a,0,2);
  csubstr($str, $a, 2,2)
  由于载取位置指向“中”的右字节,可能会是这样的结果
  1, 2
  用本函数会产生正确的结果
  1中, 2
  */
  # start 开始位置,从0开始
  # long = 0 则从start 一直取到字符串尾
  # ltor = true 时从左到右取字符,false 时到右到左取字符
  # $cn_len 中文字符按字节取还是字数取,如果按字数取,则一个中文当一个字节计算
  
  function csubstr(&$str, $start=0, $long=0, $ltor=true, $cn_len=2) {
  if($long == 0) $long = strlen($str);
  if($ltor == false) $str = cstrrev($str);
  
  if($cn_len == 1) {
  
  for($i=0, $fs=0; $i  $i += (ord($str[$fs])   for($i=0, $fe=$fs; $i  $i += (ord($str[$fe])   $long = $fe - $fs;
  
  }
  else {
  
  $fs = (is_chinese($str, $start) == 1) ? $start - 1 : $start;
  $fe = $long + $start - 1;
  $end = ( is_chinese($str, $fe) == -1 ) ? $fe -1 : $fe;
  $long = $end - $fs + 1;
  }
  
  $f_str = substr($str, $fs, $long);
  if($ltor == false) $f_str = cstrrev($f_str);
  
  return $f_str;
  }
  
  # 取左字符串
  # 当cn_len == 2 时 $long 取左边多少个字,反之则取左边多少个字节
  function cleft(&$str, $long, $cn_len=2) {
  $f_str = csubstr($str, 0, $long, true, $cn_len);
  return $f_str;
  }
  
  # 取右字符串
  function cright(&$str, $long, $cn_len=2) {
  $f_str = cstrrev($str);
  $f_str = csubstr($f_str, 0, $long, true, $cn_len);
  $f_str = cstrrev($f_str);
  return $f_str;
  }
  # 对含有中文字符的文章分行格式化
  # 再也不会发生因换行问题而产生的种种问题啦!!!
  # 注:文章的每一行必须用 n (chr(13))进行分行
  # $width 每行多少字符
  # $br 将 每行用什么字符当结束符
  
  function ctext_wrap(&$text, $width=60, $br="
") {
Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools