Home  >  Article  >  Backend Development  >  PHP Development Tips (10) - How to intercept Chinese strings without garbled characters

PHP Development Tips (10) - How to intercept Chinese strings without garbled characters

黄舟
黄舟Original
2017-03-25 13:47:511856browse

During development, we often intercept strings as needed. If it is a string of English strings, it is fine, and there will be no garbled characters when we intercept it; but if it is a Chinese string, many times it will be intercepted based on the intercepted string. If the length is inappropriate, garbled characters will appear. Let’s implement a method to intercept Chinese strings without garbled characters:

<?php  
  
/** 
 * ======================================= 
 * Created by Zhihua_W. 
 * Author: Zhihua_W 
 * Date: 2017/1/7 0009 
 * Time: 下午 4:10 
 * Project: PHP开发小技巧 
 * Power: 实现中文字串截取无乱码的方法 
 * ======================================= 
 */  
  
/** 
 * 实现中文字串截取无乱码的方法 
 * @param int $start 起始位置 
 * @param int $length 长度 
 * @return string 
 */  
function getSubstr($string, $start, $length)  
{  
    if (mb_strlen($string, &#39;utf-8&#39;) > $length) {  
        $str = mb_substr($string, $start, $length, &#39;utf-8&#39;);  
        return $str . &#39;...&#39;;  
    } else {  
        return $string;  
    }  
}  
  
?>

Related articles:

A small function that inserts a string at a specified position in the string

php custom interception of Chinese strings-utf8 version

Detailed code explanation of the calculation formula for string format through eval in php

The above is the detailed content of PHP Development Tips (10) - How to intercept Chinese strings without garbled characters. 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