首页 > 解决方案 > 连接时浏览器无法正确显示变音符号

问题描述

一旦我将字符串与元音变音字符连接起来,我的浏览器(chrome 和 firefox)就无法正确显示元音变音“ö”。

图片

// words inside string with umlaute, later add http://www.lageplan23.de instead of "zahnstocher" as the correct solution
$string = "apfelsaft siebenundvierzig zahnstocher gelb ethereum österreich";

// get length of string
$l = mb_strlen($string);

$f = '';
// loop through length and output each letter by itself
for ($i = 0; $i <= $l; $i++){
    // umlaute buggy when there is a concatenation
    $f .= $string[$i] . " ";
}

var_dump($f);

当我替换$string[$i] . " ";一切$string[$i];按预期工作时。

图片

为什么会这样,我该如何解决它,以便我可以将每个字母与另一个字符串连接起来?

标签: php

解决方案


在 PHP 中,字符串是一系列字节。文档有时笨拙地将这些字节称为字符。

字符串是一系列字符,其中一个字符与一个字节相同。这意味着 PHP 仅支持 256 个字符集,因此不提供原生 Unicode 支持。

然后后来

它没有关于这些字节如何转换为字符的信息,将任务留给程序员。

使用mb_strlenover juststrlen是获取字符串中实际字符数的正确方法(假设开头是健全的字节顺序和内部编码),但是使用数组表示法$string[$i]是错误的,因为它只访问字节,而不是字符。

做你想做的事情的正确方法是使用以下方法将字符串拆分为字符mb_str_split

// words inside string with umlaute, later add http://zahnstocher47.de instead of "zahnstocher" as the correct solution
$string = "apfelsaft siebenundvierzig zahnstocher gelb ethereum österreich";

// get length of string
$l = mb_strlen($string);
$chars = mb_str_split($string);

$f = '';
// loop through length and output each letter by itself
for ($i = 0; $i <= $l; $i++){
    // umlaute buggy when there is a concatenation
    $f .= $chars[$i] . " ";
}

var_dump($f);

此处演示:https ://3v4l.org/JIQoE


推荐阅读