文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>php中文字符截取完美解决方案

php中文字符截取完美解决方案

时间:2007-06-10  来源:sdqdgaopeng


函数巧妙地运用了正则表达式, 用起来很方便, 就像 substr 的用法一样, 可以正向截取也可反相截取, 思路值得学习.
PHP代码:

function c_substr($string, $from, $length = null){
   
preg_match_all
('/[x80-xff]?./', $string, $match);
    if(
is_null
($length)){
        $result =
implode
('',
array_slice
($match[0], $from));
    }else{
        $result =
implode
('',
array_slice
($match[0], $from, $length));
    }
    return $result;
}
$str = "zhon华人min共和guo";
$from = 3;
$length = 7;
echo
(c_substr($str, $from, $length));
// 输出: n华人min共
//还有utf-8的
/*
Regarding windix's function to handle UTF-8 strings:
one can use the "u" modifier on the regular expression so that the pattern string is treated as UTF-8
(available from PHP 4.1.0 or greater on Unix and from PHP 4.2.3 on win32).
This way the function works for other encodings too (like Greek for example).
The modified function would read like this:
*/
function utf8_substr($str,$start) {
$null = "";
   
preg_match_all
("/./u", $str, $ar);
   if(
func_num_args
() >= 3) {
       $end =
func_get_arg
(2);
       return
join
($null,
array_slice
($ar[0],$start,$end));
   } else {
       return
join
($null,
array_slice
($ar[0],$start));
   }
}
?>
  之二:


/***************************************************/
/*                                                                     */
/*  Author:                                                     */
/*  HomePage: www..com                                          */
/*  Email: [email protected]                                             */
/*  QQ:1984412                                                         */
/*                                                                     */
/***************************************************/

function get_substr($string,$start='0',$length='')
{
$start = (int)$start;
$length = (int)$length;
$i = 0;
if(!$string)
{
  return;
}
if($start>=0)
{
  while($i$start)
  {
   if(
ord
($string[$i])>127)
   {
    $i = $i+2;
   }
   else
   {
    $i++;
   }
  }
  $start = $i;
  if($length=='')
  {
   return
substr
($string,$start);
  }
  elseif($length>0)
  {
   $end = $start+$length;
   while($i$end)
   {
    if(
ord
($string[$i])>127)
    {
     $i = $i+2;
    }
    else
    {
     $i++;
    }
   }
   if($end != $i-1)
   {
    $end = $i;
   }
   else
   {
    $end--;
   }
   $length = $end-$start;
   return
substr
($string,$start,$length);
  }
  elseif($length==0)
  {
   return;
  }
  else
  {
   $length =
strlen
($string)-
abs
($length)-$start;
   return get_substr($string,$start,$length);
  }
}
else
{
  $start =
strlen
($string)-
abs
($start);
  return get_substr($string,$start,$length);
}
}

?>

相关阅读 更多 +
排行榜 更多 +
合合合军团

合合合军团

策略塔防 下载
街头滑板

街头滑板

体育竞技 下载
武者生存

武者生存

体育竞技 下载