Home  >  Article  >  Backend Development  >  Detailed explanation of php substr() function processing in Chinese

Detailed explanation of php substr() function processing in Chinese

怪我咯
怪我咯Original
2017-07-16 10:35:042554browse

substr()Function can obtain the specified length substring of string, but when encountering Chinese, garbled characters may be generated at the end of the new string , the following function converts a string longer than $len to end with "..." and removes garbled characters.

用法:$new = getsubstring($old,20); 

function getsubstring($str,$len) 
{ 
    for($i = 0;$i <$end;$i++) 
    { 
        if ($i >=0 AND $i <$end) 
        { 
            if(ord(substr($str,$i,1)) > 0xa1)  
                $result_str.=substr($str,$i,2); 
            else 
                $result_str.=substr($str,$i,1); 
        } 
        if(ord(substr($str,$i,1)) > 0xa1) 
            $i++; 
    } 
    if(strlen($str)<=$end) 
        return $result_str; 
    else 
        return $result_str."..."; 
}

The above is the detailed content of Detailed explanation of php substr() function processing in Chinese. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:PHP time processing codeNext article:PHP time processing code