Home  >  Article  >  Backend Development  >  PHP string interception (application and extension of substr)

PHP string interception (application and extension of substr)

WBOY
WBOYOriginal
2016-07-25 08:59:47933browse
Chinese or English strings can be intercepted in PHP. English is slightly simpler and Chinese is slightly more complex. This article introduces the substr function and expands the function. Friends in need can refer to it.

PHP does not have a directly available substring function, but it does have a substr function.

<?
$a="12me46";
echo(substr($a,2,2));//输出me
?> 

substr() function returns a part of a string. substr(string,start,length) string: the string to be intercepted start: Positive number - starts at the specified position in the string Negative number - starts at the specified position from the end of the string 0 - Start at the first character in the string length: Optional. Specifies the length of the string to be returned. The default is until the end of the string. Positive number - returned from the position of the start parameter Negative number - returned from the end of the string

When php intercepts Chinese strings, you need to extend the function yourself, for example:

<?php
//中文字符串截取
//http://bbs.it-home.org
function msubstr($str,$start=0,$length,$charset="utf-8",$suffix=true)
{
switch($charset){
 case 'utf-8':$char_len=3;break;
 case 'UTF8':$char_len=3;break;
 default:$char_len=2;
}
//小于指定长度,直接返回
if(strlen($str)<=($length*$char_len)){ 
   return $str;
}
if(function_exists("mb_substr")){   
   $slice= mb_substr($str, $start, $length, $charset);
}else if(function_exists('iconv_substr')){
   $slice=iconv_substr($str,$start,$length,$charset);
}else{ 
   $re['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
 $re['gbk']    = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
 $re['big5']   = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
 preg_match_all($re[$charset], $str, $match);
 $slice = join("",array_slice($match[0], $start, $length));
 }
    if($suffix) 
 return $slice."…";
    return $slice;
}
?>

I hope the above code will be helpful to everyone.



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