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, 'utf-8') > $length) { $str = mb_substr($string, $start, $length, 'utf-8'); return $str . '...'; } 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!