Maison développement back-end tutoriel php ThinkPHP+Smarty模板中截取包含中英文混同的字符串乱码的解决方案

ThinkPHP+Smarty模板中截取包含中英文混同的字符串乱码的解决方案

Jun 13, 2016 pm 12:29 PM
bytes length return string

ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案

好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下:

出现乱码的原因:

对于字符串的截取,truncate函数只适合英文用户,对与中文用户来说,使用 truncate会出现乱码,而且对于中文英文混合串来说,截取同样个数的字符串,实际显示长度上却不同,一个中文的长度大致相当于两个英文的长度。此外,truncate不能同时兼容GB2312、UTF-8等编码。

解决方法:自己写一个扩展类使用

ThinkPHP使用的smarty的truncate变量调节器所在的类文件位置:ThinkPHP\Library\Vendor\Smarty\plugins,其中有一个就是modifier.truncate.php,我们不用这个,我们自己写一个来实现

文件名:modifier.smartTruncate.php

 

<span style="color: #000000;">php</span><span style="color: #008000;">/*</span><span style="color: #008000;">* * 中英文多编码字符串截取</span><span style="color: #008000;">*/</span><span style="color: #0000ff;">function</span> smartDetectUTF8(<span style="color: #800080;">$string</span><span style="color: #000000;">){    </span><span style="color: #0000ff;">static</span> <span style="color: #800080;">$result</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();    </span><span style="color: #0000ff;">if</span>(! <span style="color: #008080;">array_key_exists</span>(<span style="color: #800080;">$key</span> = <span style="color: #008080;">md5</span>(<span style="color: #800080;">$string</span>), <span style="color: #800080;">$result</span><span style="color: #000000;">))    {        </span><span style="color: #800080;">$utf8</span> = "<span style="color: #000000;">            /^(?:                [\x09\x0A\x0D\x20-\x7E]                            # ASCII                | [\xC2-\xDF][\x80-\xBF]                             # non-overlong 2-byte                | \xE0[\xA0-\xBF][\x80-\xBF]                       # excluding overlongs                | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}           # straight 3-byte                | \xED[\x80-\x9F][\x80-\xBF]                      # excluding surrogates                | \xF0[\x90-\xBF][\x80-\xBF]{2}                 # planes 1-3                | [\xF1-\xF3][\x80-\xBF]{3}                          # planes 4-15                | \xF4[\x80-\x8F][\x80-\xBF]{2}                  # plane 16            )+$/xs        </span>"<span style="color: #000000;">;        </span><span style="color: #800080;">$result</span>[<span style="color: #800080;">$key</span>] = <span style="color: #008080;">preg_match</span>(<span style="color: #008080;">trim</span>(<span style="color: #800080;">$utf8</span>), <span style="color: #800080;">$string</span><span style="color: #000000;">);    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$result</span>[<span style="color: #800080;">$key</span><span style="color: #000000;">];}</span><span style="color: #0000ff;">function</span> smartStrlen(<span style="color: #800080;">$string</span><span style="color: #000000;">){    </span><span style="color: #800080;">$result</span> = 0<span style="color: #000000;">;    </span><span style="color: #800080;">$number</span> = smartDetectUTF8(<span style="color: #800080;">$string</span>) ? 3 : 2<span style="color: #000000;">;    </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span> = 0; <span style="color: #800080;">$i</span> strlen(<span style="color: #800080;">$string</span>); <span style="color: #800080;">$i</span> += <span style="color: #800080;">$bytes</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$bytes</span> = <span style="color: #008080;">ord</span>(<span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$i</span>, 1)) > 127 ? <span style="color: #800080;">$number</span> : 1<span style="color: #000000;">;        </span><span style="color: #800080;">$result</span> += <span style="color: #800080;">$bytes</span> > 1 ? 1.0 : 0.5<span style="color: #000000;">;    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$result</span><span style="color: #000000;">;}</span><span style="color: #0000ff;">function</span> smartSubstr(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$start</span>, <span style="color: #800080;">$length</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">){    </span><span style="color: #800080;">$result</span> = ''<span style="color: #000000;">;    </span><span style="color: #800080;">$number</span> = smartDetectUTF8(<span style="color: #800080;">$string</span>) ? 3 : 2<span style="color: #000000;">;    </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$start</span> )    {        <span style="color: #800080;">$start</span> = <span style="color: #008080;">max</span>(smartStrlen(<span style="color: #800080;">$string</span>) + <span style="color: #800080;">$start</span>, 0<span style="color: #000000;">);    }    </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span> = 0; <span style="color: #800080;">$i</span> strlen(<span style="color: #800080;">$string</span>); <span style="color: #800080;">$i</span> += <span style="color: #800080;">$bytes</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$start</span> )        {            <span style="color: #0000ff;">break</span><span style="color: #000000;">;        }        </span><span style="color: #800080;">$bytes</span> = <span style="color: #008080;">ord</span>(<span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$i</span>, 1)) > 127 ? <span style="color: #800080;">$number</span> : 1<span style="color: #000000;">;        </span><span style="color: #800080;">$start</span> -= <span style="color: #800080;">$bytes</span> > 1 ? 1.0 : 0.5<span style="color: #000000;">;    }    </span><span style="color: #0000ff;">if</span>(<span style="color: #008080;">is_null</span>(<span style="color: #800080;">$length</span><span style="color: #000000;">))    {        </span><span style="color: #800080;">$result</span> = <span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$i</span><span style="color: #000000;">);    }    </span><span style="color: #0000ff;">else</span><span style="color: #000000;">    {        </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$j</span> = <span style="color: #800080;">$i</span>; <span style="color: #800080;">$j</span> strlen(<span style="color: #800080;">$string</span>); <span style="color: #800080;">$j</span> += <span style="color: #800080;">$bytes</span><span style="color: #000000;">)        {            </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$length</span> )            {                <span style="color: #0000ff;">break</span><span style="color: #000000;">;            }            </span><span style="color: #0000ff;">if</span>((<span style="color: #800080;">$bytes</span> = <span style="color: #008080;">ord</span>(<span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$j</span>, 1)) > 127 ? <span style="color: #800080;">$number</span> : 1) > 1<span style="color: #000000;">)            {                </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$length</span> )                {                    <span style="color: #0000ff;">break</span><span style="color: #000000;">;                }                </span><span style="color: #800080;">$result</span> .= <span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$j</span>, <span style="color: #800080;">$bytes</span><span style="color: #000000;">);                </span><span style="color: #800080;">$length</span> -= 1.0<span style="color: #000000;">;            }            </span><span style="color: #0000ff;">else</span><span style="color: #000000;">            {                </span><span style="color: #800080;">$result</span> .= <span style="color: #008080;">substr</span>(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$j</span>, 1<span style="color: #000000;">);                </span><span style="color: #800080;">$length</span> -= 0.5<span style="color: #000000;">;            }        }    }    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$result</span><span style="color: #000000;">;}</span><span style="color: #0000ff;">function</span> smarty_modifier_smartTruncate(<span style="color: #800080;">$string</span>, <span style="color: #800080;">$length</span> = 80, <span style="color: #800080;">$etc</span> = '...',<span style="color: #800080;">$break_words</span> = <span style="color: #0000ff;">false</span>, <span style="color: #800080;">$middle</span> = <span style="color: #0000ff;">false</span><span style="color: #000000;">){    </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$length</span> == 0<span style="color: #000000;">)        </span><span style="color: #0000ff;">return</span> ''<span style="color: #000000;">;    </span><span style="color: #0000ff;">if</span> (smartStrlen(<span style="color: #800080;">$string</span>) > <span style="color: #800080;">$length</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$length</span> -= smartStrlen(<span style="color: #800080;">$etc</span><span style="color: #000000;">);        </span><span style="color: #0000ff;">if</span> (!<span style="color: #800080;">$break_words</span> && !<span style="color: #800080;">$middle</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$string</span> = <span style="color: #008080;">preg_replace</span>('/\s+?(\S+)?$/', '', smartSubstr(<span style="color: #800080;">$string</span>, 0, <span style="color: #800080;">$length</span>+1<span style="color: #000000;">));        }        </span><span style="color: #0000ff;">if</span>(!<span style="color: #800080;">$middle</span><span style="color: #000000;">) {            </span><span style="color: #0000ff;">return</span> smartSubstr(<span style="color: #800080;">$string</span>, 0, <span style="color: #800080;">$length</span>).<span style="color: #800080;">$etc</span><span style="color: #000000;">;        } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {            </span><span style="color: #0000ff;">return</span> smartSubstr(<span style="color: #800080;">$string</span>, 0, <span style="color: #800080;">$length</span>/2) . <span style="color: #800080;">$etc</span> . smartSubstr(<span style="color: #800080;">$string</span>, -<span style="color: #800080;">$length</span>/2<span style="color: #000000;">);        }    } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$string</span><span style="color: #000000;">;    }}</span>?>
Copier après la connexion

 

注意:在判断字符长度时,一个中文字符算1.0,一个英文字符算0.5,截取子字符串时不会出现参差不齐的情况.

使用方法:

{<span style="color: #800080;">$content</span>|smartTruncate:5:"..."}
Copier après la connexion

ok,测试没有问题有问欢迎指出

 

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)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 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

Explication détaillée de l'utilisation de return en langage C Explication détaillée de l'utilisation de return en langage C Oct 07, 2023 am 10:58 AM

L'utilisation de return en langage C est la suivante : 1. Pour les fonctions dont le type de valeur de retour est void, vous pouvez utiliser l'instruction return pour terminer l'exécution de la fonction plus tôt. 2. Pour les fonctions dont le type de valeur de retour n'est pas void, la fonction de ; l'instruction return sert à terminer l'exécution de la fonction.Le résultat est renvoyé à l'appelant ;3. Terminer l'exécution de la fonction plus tôt que prévu.À l'intérieur de la fonction, nous pouvons utiliser l'instruction return pour terminer l'exécution de la fonction plus tôt. si la fonction ne renvoie pas de valeur.

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.

Méthodes d'activation manuelle et didacticiels HWID V 2.2 Méthodes d'activation manuelle et didacticiels HWID V 2.2 Oct 20, 2023 pm 07:17 PM

Ceci est destiné aux utilisateurs qui souhaitent effectuer une activation manuelle. Si vous avez besoin d'aide avec un outil pour ce faire, vérifiez ici. Nous pouvons diviser le processus d'activation manuelle en deux parties. 1- À partir du fichier batch prêt à l’emploi, assurez-vous qu’Internet est activé. Ouvrez Windows Powershell en tant qu'administrateur et saisissez ce qui suit pour répertorier les commandes dans l'ordre dans lequel elles sont données. Entrez la clé (remplacez par la clé de la liste ci-dessus) Utilisez la commande suivante &lt;key&gt;slmgr/ipk&lt;key&gt; Téléchargez le ticket universel à partir d'ici et extrayez le fichier téléchargé. Entrez maintenant le code suivant dans Powershell (Get-ItemProper

Quel est l'ordre d'exécution des instructions return et enfin en Java ? Quel est l'ordre d'exécution des instructions return et enfin en Java ? Apr 25, 2023 pm 07:55 PM

Code source : publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}# Sortie La sortie du code ci-dessus peut simplement conclure : return est exécuté avant finalement. Jetons un coup d'œil à ce qui se passe au niveau du bytecode. Ce qui suit intercepte une partie du bytecode de la méthode case1 et compare le code source pour annoter la signification de chaque instruction dans

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 :

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.

Comment utiliser la méthode split dans Java String Comment utiliser la méthode split dans Java String May 02, 2023 am 09:37 AM

La méthode split dans String utilise la méthode split() de String pour diviser la chaîne en fonction des caractères ou des chaînes entrants et renvoyer le tableau divisé. 1. Utilisation générale Lors de l'utilisation de caractères généraux, tels que @ ou, comme séparateurs : Stringaddress="Shanghai@Shanghai City@Minhang District@Wuzhong Road";String[]splitAddr=address.split("@");System .out. println(splitAddr[0]+splitAddr[1]+splitAddr[2]+splitAddr[3

See all articles