在UTF-8编码的字符串上使用str_split [英] Using str_split on a UTF-8 encoded string
问题描述
我目前正在研究一个项目,我不使用常规的MySQL查询,而是继续学习PDO.
I'm currently working on a project, and instead of using regular MySQL queries I thought I'd go ahead and learn how to use PDO.
我有一个称为参赛者的表,数据库,表和所有列均位于utf-8中.我的参赛者表中有10个条目,它们的名称"列中包含诸如åäö之类的字符.
I have a table called contestants, both the database, the table, and all of the columns are in utf-8. I have ten entries in the contestant table, and their column "name" contains characters such as åäö.
现在,当我从数据库中获取一个条目并使用var_dump的名称时,我得到了一个很好的结果,一个包含所有特殊字符的字符串.但是我需要做的是将字符串按字符分开,然后将它们放入一个数组中,然后重新排列.
Now, when I fetch an entry from the database, and var_dump the name, I get a good result, a string with all the special characters intact. But what I need to do is to split the string by characters, to get them in an array that I then shuffle.
例如,我有以下字符串: 测试ÅÄÖTåän
For instance, I have this string: Test ÅÄÖ Tåän
当我运行str_split时,我获得了数组中自己的每个键.唯一的问题是所有特殊字符都将显示为: ,这意味着数组将如下所示:
And when I run str_split I get each character in it's own key in an array. The only issue is that all the special characters display as this: �, meaning the array will be like this:
Array
(
[0] => T
[1] => e
[2] => s
[3] => t
[4] =>
[5] => �
[6] => �
[7] => �
[8] => �
[9] => �
[10] => �
[11] =>
[12] => T
[13] => �
[14] => �
[15] => �
[16] => �
[17] => n
)
如您所见,它不仅弄乱了字符,而且还在str_split进程中复制了它们.我尝试了几种分割字符串的方法,但是它们都有相同的问题.当我在分割之前输出字符串时,它会很好地显示特殊字符.
As you can see, it not only messes up the characters, but it also duplicates them in str_split process. I've tried several ways to split the string, but they all have the same issue. When I output the string before the split, it shows the special characters just fine.
这是我的dbConn.php代码:
This is my dbConn.php code:
//需要配置文件: require_once('config.inc.php');
// Require config file: require_once('config.inc.php');
// Start PDO connection:
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf-8", $dbUser, $dbPass);
$dbHandle -> exec("SET CHARACTER SET utf8");
// Set error reporting:
$dbHandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
这是我用来从数据库中获取并循环的代码:
And this is the code that I use to fetch from the database and loop:
// Require files:
require_once('dbConn.php');
// Get random artist:
$artist = $dbHandle->query("SELECT * FROM ".ARTIST_TABLE." WHERE id = 11 ORDER BY RAND() LIMIT 1");
$artist->setFetchMode(PDO::FETCH_OBJ);
$artist = $artist->fetch();
var_dump($artist->name);
// Split name:
$artistChars = str_split($artist->name);
我正在连接utf-8,我的php文件是utf-8 没有BOM ,并且此页面上没有其他特殊字符共享此问题.可能是什么问题,或者我做错了什么?
I'm connecting with utf-8, my php file is utf-8 without BOM and no other special characters on this page share this issue. What could be wrong, or what am I doing wrong?
推荐答案
str_split
不适用于多字节字符,它只会返回第一个字节-从而使您的字符无效.您可以使用 mb_split
.
这篇关于在UTF-8编码的字符串上使用str_split的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!