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

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

黄舟
Release: 2023-03-06 13:54:01
Original
1906 people have browsed it

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;  
    }  
}  
  
?>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template