EverKB

Knowledge Base Ever

PHP對字符串截取後文本產生了亂碼

2019-11-21 10:16:54

標籤: PHP,substr,mb_substr, 亂碼

通常我們會使用substr對字符串進行截取,如果是全部英文的字符串一切正常,但是含有其他文字的時候,截取後會偶爾產生亂碼的現象。其實是由於字符存儲的時候一個文字會佔用不止一個字節,而substr函數的截取是按字節進行截取的,所以當我們把一個文字的多個字節截斷以後就會產生亂碼的現象了。其實PHP中mb_substr函數就是針對這個場景的,它支持按照字符串編碼來進行字符串截取。
mb_substr($str, $start, $length, $encoding)

mb_substr('XXXXXXXX', 0, 4, 'utf-8');
當然除了字符串截取意外,獲取字符串長度也是有相應的支持編碼格式的函數
mb_strlen($str, $encoding)

標籤

CentOS7 CentOS PHP Linux Python3 Python MySQL YUM JavaScript MariaDB Redis MySQL8 caching_sha2_password HTML mysql_native_password PHP7 CSS SQLAlchemy absolute Deepin jemalloc mysqlclient Shadowsocks toggle convert FuelPHP PHPUnit Framework ss5.passwd at-symbol Error Control Operator margin password SOCKET vps daemon process IIS MongoDB4 sudoers center Fatal Errors Phalcon SQL Server 2017 WiFi .htaccess DATE_SUB set_error_handler TestCase Compiling PHP frequency conflict PHPUnit ss5.conf apr Elasticsearch7.3 particles.js Slim Vincent Garreau daemon HTTP MongoDB Sudo Failed to build these modules: _uuid pg_bha.conf SQL Server width DATE_ADD ip command MySQL-python scrollbar Tcp BBR Compiling Apache Frameworks PHPStorm ss5-3.8.9 Apache2.4 Elasticsearch libpython3.7m.so.1.0 NodeJs show VIM CURLOPT_POSTFIELDS Minimal ISO substr Bluetooth Failed to build these modules: _ctypes PECL SQL Date Funcitons Wi-Fi date sub INTERVAL root Tag Cloud CodeIgniter font-size ss5 apache httpd dual network interfaces Laravel node.js ShadowsocksR vertical-align CURLFille horiz-align PyCharm SUBDATE BarManager exec mb_substr PEAR SOCKS5 Proxy Server WebStorm date add IntelliJIDEA remi Tag Chrome find PHP5.5 src Apache du jQuery nginx Shadowsocks-Python V2Ray cURL hide PostgreSQL sub folder availability eth0 MariaDB10.4 pdo_sqlsrv SOCKS5 Web Server date Install MongoDB mssql-tools register_shutdown_function Symfony File Upload php-fpm sqlsrv Zend Framework ADDDATE DevExpress JetBrain network interface Shadowsocks-Libev unixODBC-devel height Port 80 string Aura error_get_last password policy requirements SOCKS Web Development data INDENTIFIED BY msodbcsql Redis5 SVN Fedora Media Writer