問題描述
我目前正在處理一個項目,我想我應該繼續學習如何使用 PDO,而不是使用常規的 MySQL 查詢.
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.我在參賽者表中有十個條目,它們的名稱"列包含 ??? 等字符.
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
不適用于 multi-byte 字符,它只會返回第一個字節 - 從而使您的字符無效.你可以使用 mb_split
.
這篇關于在 UTF-8 編碼的字符串上使用 str_split的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!