Maison développement back-end tutoriel php 分割gbk中文出现乱码的有关问题解决

分割gbk中文出现乱码的有关问题解决

Jun 13, 2016 pm 12:28 PM
array encoding explode list string

分割gbk中文出现乱码的问题解决

近日遇到一个神奇的字“弢(tao)”。

具体的过程是这样的:

<span style="color: #008080;">1</span> <span style="color: #800080;">$list</span> = <span style="color: #008080;">explode</span>('|', 'abc弢|bc'<span style="color: #000000;">);</span><span style="color: #008080;">2</span> <span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$list</span>);
Copier après la connexion

取得这个分割的结果。

和想象不同,结果居然是这样:

<span style="color: #0000ff;">array</span>(3<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">string</span>(4) "<span style="color: #000000;">abc?  [1]=>  string(0) </span>""<span style="color: #000000;">  [2]=>  string(2) </span>"bc"<span style="color: #000000;">}</span>
Copier après la connexion
Copier après la connexion

出现了乱码,而且莫名其妙的出现了一个空元素。

究其原因,原来这个字“弢”的gbk编码是8f7c,而|的ASCII是7c,这样explode就把弢的第二ASCII作为|切割了。

既然是双字节的问题,我们用mbstring解决好了。

可惜,php并没有mb_explode这种函数,找了找,找到一个mb_split。

<span style="color: #0000ff;">array</span> mb_split ( <span style="color: #0000ff;">string</span> <span style="color: #800080;">$pattern</span> , <span style="color: #0000ff;">string</span> <span style="color: #800080;">$string</span> [, int <span style="color: #800080;">$limit</span> = -1 ] )
Copier après la connexion

没有声明编码的地方。仔细一看,他是通过mb_regex_encoding声明编码的。

于是写出以下的代码:

<span style="color: #008080;">1</span> mb_regex_encoding('gbk'<span style="color: #000000;">);</span><span style="color: #008080;">2</span> <span style="color: #800080;">$list</span> = mb_split('\|', 'abc弢|bc'<span style="color: #000000;">);</span><span style="color: #008080;">3</span> <span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$list</span>);
Copier après la connexion

结果php报错,mb_regex_encoding不认识gbk,囧。

那就使用它认识的:

<span style="color: #008080;">1</span> mb_regex_encoding('gb2312'<span style="color: #000000;">);</span><span style="color: #008080;">2</span> <span style="color: #800080;">$list</span> = mb_split('\|', 'abc弢|bc'<span style="color: #000000;">);</span><span style="color: #008080;">3</span> <span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$list</span>);
Copier après la connexion

结果:

<span style="color: #0000ff;">array</span>(3<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">string</span>(4) "<span style="color: #000000;">abc?  [1]=>  string(0) </span>""<span style="color: #000000;">  [2]=>  string(2) </span>"bc"<span style="color: #000000;">}</span>
Copier après la connexion
Copier après la connexion

发现,这种方法并没有什么用处。、

至于原因?“弢”这个字居然不在GB2312的编码集里面!!!!!但是有这个字的编码集(GBK, GB18030)这个函数都不支持!!!!!

既然这个不好用,也许万能的正则表达式是ok的。于是得到以下代码:

<span style="color: #008080;">1</span> <span style="color: #008080;">var_dump</span>(<span style="color: #008080;">preg_match_all</span>('/([^\|])*/', 'abc弢|bc', <span style="color: #800080;">$matches</span><span style="color: #000000;">));</span><span style="color: #008080;">2</span> <span style="color: #008080;">var_dump</span>(<span style="color: #800080;">$matches</span>);
Copier après la connexion

结果:

int(2<span style="color: #000000;">)</span><span style="color: #0000ff;">array</span>(2<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">array</span>(2<span style="color: #000000;">) {    [</span>0]=>    <span style="color: #0000ff;">string</span>(4) "<span style="color: #000000;">abc?    [1]=>    string(2) </span>"bc"<span style="color: #000000;">  }  [1]=>  array(2) {    [0]=>    string(1) </span>"?<span style="color: #000000;">    [</span>1]=>    <span style="color: #0000ff;">string</span>(1) "c"<span style="color: #000000;">  }}</span>
Copier après la connexion

好吧,我想多了。

现在研究一下,如何用正则描述这个场景。

参考一下,鸟哥大神的博客:分割GBK中文遭遇乱码的解决。遗憾的是,正则能力比较low的我,还是想不出来合适的正则表达式(如果有想出这个正则表达式的大神们,希望可以告诉我)。

没办法,思来想去,只好用substr了:

<span style="color: #008080;"> 1</span> <span style="color: #0000ff;">function</span> mb_explode(<span style="color: #800080;">$delimiter</span>, <span style="color: #800080;">$string</span>, <span style="color: #800080;">$encoding</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">){</span><span style="color: #008080;"> 2</span>     <span style="color: #800080;">$list</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();</span><span style="color: #008080;"> 3</span>     <span style="color: #008080;">is_null</span>(<span style="color: #800080;">$encoding</span>) && <span style="color: #800080;">$encoding</span> =<span style="color: #000000;"> mb_internal_encoding();</span><span style="color: #008080;"> 4</span>     <span style="color: #800080;">$len</span> = mb_strlen(<span style="color: #800080;">$delimiter</span>, <span style="color: #800080;">$encoding</span><span style="color: #000000;">);</span><span style="color: #008080;"> 5</span>     <span style="color: #0000ff;">while</span>(<span style="color: #0000ff;">false</span> !== (<span style="color: #800080;">$idx</span> = mb_strpos(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$delimiter</span>, 0, <span style="color: #800080;">$encoding</span><span style="color: #000000;">))){</span><span style="color: #008080;"> 6</span>         <span style="color: #800080;">$list</span>[] = mb_substr(<span style="color: #800080;">$string</span>, 0, <span style="color: #800080;">$idx</span>, <span style="color: #800080;">$encoding</span><span style="color: #000000;">);</span><span style="color: #008080;"> 7</span>         <span style="color: #800080;">$string</span> = mb_substr(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$idx</span> + <span style="color: #800080;">$len</span>, <span style="color: #0000ff;">null</span>, <span style="color: #800080;">$encoding</span><span style="color: #000000;">);</span><span style="color: #008080;"> 8</span> <span style="color: #000000;">    }   </span><span style="color: #008080;"> 9</span>     <span style="color: #800080;">$list</span>[] = <span style="color: #800080;">$string</span><span style="color: #000000;">;</span><span style="color: #008080;">10</span>     <span style="color: #0000ff;">return</span> <span style="color: #800080;">$list</span><span style="color: #000000;">; </span><span style="color: #008080;">11</span> } 
Copier après la connexion

测试代码:

<span style="color: #008080;">1</span> <span style="color: #800080;">$a</span> = 'abc弢|bc'<span style="color: #000000;">;</span><span style="color: #008080;">2</span> <span style="color: #008080;">3</span> <span style="color: #008080;">var_dump</span>(mb_explode('|', <span style="color: #800080;">$a</span>, 'gbk'<span style="color: #000000;">));</span><span style="color: #008080;">4</span> <span style="color: #008080;">var_dump</span>(mb_explode('bc', <span style="color: #800080;">$a</span>, 'gbk'<span style="color: #000000;">));</span><span style="color: #008080;">5</span> <span style="color: #008080;">var_dump</span>(mb_explode('弢', <span style="color: #800080;">$a</span>, 'gbk'));
Copier après la connexion

结果:

<span style="color: #0000ff;">array</span>(2<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">string</span>(5) "abc弢"<span style="color: #000000;">  [</span>1]=>  <span style="color: #0000ff;">string</span>(2) "bc"<span style="color: #000000;">}</span><span style="color: #0000ff;">array</span>(3<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">string</span>(1) "a"<span style="color: #000000;">  [</span>1]=>  <span style="color: #0000ff;">string</span>(3) "弢|"<span style="color: #000000;">  [</span>2]=>  <span style="color: #0000ff;">string</span>(0) ""<span style="color: #000000;">}</span><span style="color: #0000ff;">array</span>(2<span style="color: #000000;">) {  [</span>0]=>  <span style="color: #0000ff;">string</span>(3) "abc"<span style="color: #000000;">  [</span>1]=>  <span style="color: #0000ff;">string</span>(3) "|bc"<span style="color: #000000;">}</span>
Copier après la connexion

这样就可以得到正确的结果了。

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Où trouver la courte de la grue à atomide atomique
1 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Convertissez les types de données de base en chaînes à l'aide de la fonction String.valueOf() de Java Convertissez les types de données de base en chaînes à l'aide de la fonction String.valueOf() de Java Jul 24, 2023 pm 07:55 PM

Convertir les types de données de base en chaînes à l'aide de la fonction String.valueOf() de Java Dans le développement Java, lorsque nous devons convertir les types de données de base en chaînes, une méthode courante consiste à utiliser la fonction valueOf() de la classe String. Cette fonction peut accepter les paramètres des types de données de base et renvoyer la représentation sous forme de chaîne correspondante. Dans cet article, nous explorerons comment utiliser la fonction String.valueOf() pour les conversions de types de données de base et fournirons quelques exemples de code pour

Comment convertir un tableau de caractères en chaîne Comment convertir un tableau de caractères en chaîne Jun 09, 2023 am 10:04 AM

Méthode de conversion d'un tableau de caractères en chaîne : cela peut être réalisé par affectation. Utilisez la syntaxe {char a[]=" abc d\0efg ";string s=a;} pour laisser le tableau de caractères attribuer directement une valeur à la chaîne et l'exécuter. le code pour terminer la conversion.

Utilisez la fonction String.replace() de Java pour remplacer des caractères (chaînes) dans une chaîne Utilisez la fonction String.replace() de Java pour remplacer des caractères (chaînes) dans une chaîne Jul 25, 2023 pm 05:16 PM

Remplacez les caractères (chaînes) dans une chaîne à l'aide de la fonction String.replace() de Java. En Java, les chaînes sont des objets immuables, ce qui signifie qu'une fois qu'un objet chaîne est créé, sa valeur ne peut pas être modifiée. Cependant, vous pouvez rencontrer des situations dans lesquelles vous devez remplacer certains caractères ou chaînes dans une chaîne. À l'heure actuelle, nous pouvons utiliser la méthode replace() dans la classe String de Java pour implémenter le remplacement de chaîne. La méthode replace() de la classe String a deux types :

Comment implémenter l'opération Redis List en php Comment implémenter l'opération Redis List en php May 26, 2023 am 11:51 AM

Opération de liste //Insérer une valeur à partir de l'en-tête de la liste. $ret=$redis->lPush('city','guangzhou');//Insérez une valeur à partir de la fin de la liste. $ret=$redis->rPush('city','guangzhou');//Obtient les éléments dans la plage spécifiée de la liste. 0 représente le premier élément de la liste, -1 représente le dernier élément et -2 représente l'avant-dernier élément. $ret=$redis->l

Explication détaillée de 2 mots en chaîne, yyds Explication détaillée de 2 mots en chaîne, yyds Aug 24, 2023 pm 03:56 PM

Bonjour à tous, aujourd'hui je vais partager avec vous les connaissances de base de Java : String. Inutile de dire l'importance de la classe String, on peut dire que c'est la classe la plus utilisée dans notre développement back-end, il est donc nécessaire d'en parler.

Utilisez la fonction String.length() de Java pour obtenir la longueur d'une chaîne Utilisez la fonction String.length() de Java pour obtenir la longueur d'une chaîne Jul 25, 2023 am 09:09 AM

Utilisez la fonction String.length() de Java pour obtenir la longueur d'une chaîne. En programmation Java, la chaîne est un type de données très courant. Nous avons souvent besoin d'obtenir la longueur d'une chaîne, c'est-à-dire le nombre de caractères qu'elle contient. En Java, nous pouvons utiliser la fonction length() de la classe String pour obtenir la longueur d'une chaîne. Voici un exemple de code simple : publicclassStringLengthExample{publ

Trier le tableau à l'aide de la fonction Array.Sort en C# Trier le tableau à l'aide de la fonction Array.Sort en C# Nov 18, 2023 am 10:37 AM

Titre : Exemple d'utilisation de la fonction Array.Sort pour trier un tableau en C# Texte : En C#, un tableau est une structure de données couramment utilisée, et il est souvent nécessaire de trier le tableau. C# fournit la classe Array, qui possède la méthode Sort pour trier facilement les tableaux. Cet article explique comment utiliser la fonction Array.Sort en C# pour trier un tableau et fournit des exemples de code spécifiques. Tout d’abord, nous devons comprendre l’utilisation de base de la fonction Array.Sort. Tableau.Donc

Compétences en matière de conversion d'octets, de runes et de types de chaînes Golang Compétences en matière de conversion d'octets, de runes et de types de chaînes Golang May 17, 2023 am 08:21 AM

Dans la programmation Golang, les types octet, rune et chaîne sont des types de données très basiques et courants. Ils jouent un rôle important dans le traitement des opérations de données telles que les chaînes et les flux de fichiers. Lors de l'exécution de ces opérations de données, nous devons généralement les convertir les unes aux autres, ce qui nécessite la maîtrise de certaines compétences de conversion. Cet article présentera les techniques de conversion de types d'octets, de runes et de chaînes des fonctions Golang, dans le but d'aider les lecteurs à mieux comprendre ces types de données et à être capables de les appliquer habilement dans la pratique de la programmation.

See all articles