php 在 UTF-8 编码的字符串上使用 str_split
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7822461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using str_split on a UTF-8 encoded string
提问by Jonathan
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.
我目前正在做一个项目,而不是使用常规的 MySQL 查询,我想我会继续学习如何使用 PDO。
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 ???.
我有一个叫参赛者的表,数据库、表和所有列都是utf-8。我在参赛者表中有十个条目,它们的“名称”列包含诸如 ??? 之类的字符。
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.
现在,当我从数据库中获取一个条目并使用 var_dump 名称时,我得到了一个很好的结果,一个包含所有特殊字符的字符串。但是我需要做的是按字符拆分字符串,将它们放入一个数组中,然后再进行洗牌。
For instance, I have this string: Test ??? T??n
例如,我有这个字符串: Test ??? ??n
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:
当我运行 str_split 时,我将每个字符放在数组中它自己的键中。唯一的问题是所有特殊字符都显示为:?,这意味着数组将是这样的:
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
)
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.
如您所见,它不仅弄乱了字符,而且还在 str_split 过程中复制了它们。我尝试了几种拆分字符串的方法,但它们都有相同的问题。当我在拆分之前输出字符串时,它显示的特殊字符就好了。
This is my dbConn.php code:
这是我的 dbConn.php 代码:
// Require config file: require_once('config.inc.php');
// 需要配置文件: 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);
I'm connecting with utf-8, my php file is utf-8 without BOMand no other special characters on this page share this issue. What could be wrong, or what am I doing wrong?
我正在使用 utf-8 连接,我的 php 文件是没有 BOM 的utf-8并且此页面上没有其他特殊字符共享此问题。什么可能是错的,或者我做错了什么?
采纳答案by Wesley van Opdorp
回答by Leo
Mind that the utf8 declaration used in your connect-string is reported to be not working. In the comments on php.net I frequently see this alternative:
请注意,您的连接字符串中使用的 utf8 声明被报告为不起作用。在 php.net 的评论中,我经常看到这个替代方案:
$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
回答by MikeOffenbach
UTF-8 Using PDO
使用 PDO 的 UTF-8
problems when writing international (even Chinese and Thailandic) characters to the database
将国际(甚至中文和泰文)字符写入数据库时出现的问题
there may be more ways to make this work. I am not an expert, just a tech-freak, interested to understand all this. In Linux and Windows I have set up a few CMS (content-managing-systems), using a sample from the following website:
可能有更多的方法来完成这项工作。我不是专家,只是一个技术狂,有兴趣了解这一切。在 Linux 和 Windows 中,我使用来自以下网站的示例设置了一些 CMS(内容管理系统):
'http://www.elated.com/articles/cms-in-an-afternoon-php-mysql'
' http://www.elated.com/articles/cms-in-an-afternoon-php-mysql'
The sample is using PDO for insert, update and delete.
该示例使用 PDO 进行插入、更新和删除。
It took me a few hours to find a solution. Whatever I did, I always concluded differences between the data in my forms and in the phpmyadmin/heidi -views
我花了几个小时才找到解决方案。无论我做什么,我总是总结出表单中的数据和 phpmyadmin/heidi -views 中的数据之间的差异
I followed the hints of: 'https://mathiasbynens.be/notes/mysql-utf8mb4' but there was still no success
我遵循了以下提示:“ https://mathiasbynens.be/notes/mysql-utf8mb4”但仍然没有成功
In my CMS-structure there is a file 'Config.php': After reading this webpage I changed the line
在我的 CMS 结构中有一个文件 'Config.php':阅读此网页后,我更改了该行
define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings);
to
到
define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings;charset=utf8');
Now all works fine.
现在一切正常。
回答by awm
回答by Strapicarus
this work for me... hope its usefull.
这项工作对我来说......希望它有用。
ensure that the database, apache and every config was in utf8.
确保数据库、apache 和每个配置都在 utf8 中。
PDO OBJECT
PDO 对象
$dsn = 'mysql:host=' . Config::read('db.host') . ';dbname=' . config::read('db.basename') .';charset=utf8'. ';port=' . Config::read('db.port') .';connect_timeout=15';
$user = Config::read('db.user');
$password = Config::read('db.password');
$this->dbh = new PDO($dsn, $user, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
it work if not using another function like str_word_count.
如果不使用像 str_word_count 这样的其他函数,它就可以工作。
USING str_word_count you need to use utf8_decode(utf8_encode)..
使用 str_word_count 你需要使用 utf8_decode(utf8_encode)..
function cortar($str)
{
if (20>$count=str_word_count($str)) {
return $str;
}
else
{
$array = str_word_count($str,1,'.,-0123456789()+=??!"<>*??áéíóúáéíóú@|/%$#?');
$s='';
$c=0;
foreach ($array as $e) {
if (20>$c) {
if (19>$c) {
$s.=$e.' ';
}
else
{
$s.=$e;
}
}
$c+=1;
}
return utf8_decode(utf8_encode($s));
}
}
function returs string with 20 words.
函数返回 20 个单词的字符串。
回答by Shailesh Dwivedi
UTF-8 PROBLEMS & SOLUTIONS by PHP FUNCTIONS
PHP 函数的 UTF-8 问题和解决方案
1. How to Save UTF-8 Charterers (mathematical string,special chars like 92 ÷ 8 ÷ 2 = ? ) ?
1. 如何保存 UTF-8 Charterers(数学字符串,特殊字符如 92 ÷ 8 ÷ 2 = ? )?
Ans. $string =utf8_encode('92 ÷ 8 ÷ 2 = ?');
答。 $string =utf8_encode('92 ÷ 8 ÷ 2 = ?');
2. How to print UTF-8 Charterers From Database ?
2. 如何从数据库打印 UTF-8 Charterers?
Ans. echo utf8_decode($string);
答。回声 utf8_decode($string);
Note: If you do not want to do this by using encoding/decoding you can do this via.
注意:如果您不想通过使用编码/解码来做到这一点,您可以通过这样做。
1. if you are using mysqli_query() then
1. 如果你使用 mysqli_query() 那么
$conn = mysqli_connect('localhost','db_username','password','your_database_name');
mysqli_set_charset($conn,"utf8");
2.If you are using PDO then
2.如果您使用的是 PDO 那么
class Database extends PDO{
function __construct() {
parent::__construct("mysql:host=localhost;dbname=your_db_name","gurutslz_root","Your_db_password",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
}
$conn=new Database();
回答by Michael Wegman
I only had issues with text fields in my database structure, storing product descriptions. I set the field settings to blob instead of text, which solved my problem.
我的数据库结构中只有文本字段有问题,存储产品描述。我将字段设置设置为 blob 而不是文本,这解决了我的问题。