歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux資訊 >> 更多Linux >> PHP 中英文混合排版中處理字符串常用的函數

PHP 中英文混合排版中處理字符串常用的函數

日期:2017/2/27 14:23:14   编辑:更多Linux
  /*  我們在處理中文數據時,經常要處理一些情況,下面就是針對  這些情況,我做的一些函數,已經用在了實踐中    */    # 判斷某個位置是中文字符的左還是右半部分,或不是中文  # 返回值 -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



Copyright © Linux教程網 All Rights Reserved