对 UTF-8 编码字符串使用 str_split

发布于 2024-12-10 22:11:22 字数 1658 浏览 0 评论 0原文

我目前正在开发一个项目,我想我应该继续学习如何使用 PDO,而不是使用常规的 MySQL 查询。

我有一个名为“contestants”的表,数据库、表和所有列均采用 utf-8 格式。我在参赛者表中有十个条目,他们的“姓名”列包含诸如 åäö 之类的字符。

现在,当我从数据库中获取条目并 var_dump 名称时,我得到了一个很好的结果,一个包含所有特殊字符的字符串。但我需要做的是按字符拆分字符串,将它们放入一个数组中,然后进行洗牌。

例如,我有这个字符串: 测试 ÅäÖ Tåän

当我运行 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
)

如您所见,它不仅弄乱了字符,而且还在 str_split 过程中重复了它们。我尝试了多种分割字符串的方法,但它们都有相同的问题。当我在分割之前输出字符串时,它可以很好地显示特殊字符。

这是我的 dbConn.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);

这是我用来从数据库和循环中获取的代码:

// 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 currently working on a project, and instead of using regular MySQL queries I thought I'd go ahead and learn how to use 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 åäö.

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.

For instance, I have this string:
Test ÅÄÖ Tåä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:

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.

This is my dbConn.php code:

// 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);

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

酒与心事 2024-12-17 22:11:22

请注意,连接字符串中使用的 utf8 声明据报告不起作用。
在 php.net 的评论中,我经常看到这种替代方案:

$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,
                    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

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:

$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass,
                    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
涙—继续流 2024-12-17 22:11:22

str_split 不适用于多字节字符,它只会返回第一个字节 - 从而使您的字符无效。您可以使用mb_split

str_split does not work with multi-byte characters, it will only return the first byte - thus invalidating your characters. you could use mb_split.

旧情勿念 2024-12-17 22:11:22

​​UTF-8 使用 PDO

将国际(甚至中文和泰文)字符写入数据库时

问题可能有更多方法可以实现此目的。我不是专家,只是一个技术狂,有兴趣了解这一切。在 Linux 和 Windows 中,我使用以下网站中的示例设置了一些 CMS(内容管理系统):

'http://www.elated.com/articles/cms-in-an-afternoon-php-mysql'

该示例使用 PDO 进行插入、更新并删除。

我花了几个小时才找到解决方案。 得出表单中的数据与 phpmyadmin/heidi 视图中的数据之间的差异

无论我做什么,我总是根据以下提示 : 'https://mathiasbynens.be/notes/mysql-utf8mb4' 但仍然没有成功

在我的 CMS 结构中有一个文件'配置.php':
阅读此网页后,我将行更改

    define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings);

    define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings;charset=utf8');

“现在一切正常”。

UTF-8 Using PDO

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:

'http://www.elated.com/articles/cms-in-an-afternoon-php-mysql'

The sample is using PDO for insert, update and delete.

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

I followed the hints of: 'https://mathiasbynens.be/notes/mysql-utf8mb4' but there was still no success

In my CMS-structure there is a file 'Config.php':
After reading this webpage I changed the line

    define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings);

to

    define( 'DB_DSN', 'mysql:host=localhost;dbname=mythings;charset=utf8');

Now all works fine.

柒夜笙歌凉 2024-12-17 22:11:22

str_split 函数按字节拆分,而不是按字符拆分。您需要mb_split

The str_split function splits by byte, not by character. You'll need mb_split.

窝囊感情。 2024-12-17 22:11:22

这对我有用...希望它有用。

确保数据库、apache 和每个配置都是 utf8 格式。

PDO OBJECT

            $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);

如果不使用 str_word_count 等其他函数,它就可以工作。

使用 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));
    }
}

函数返回包含 20 个单词的字符串。

this work for me... hope its usefull.

ensure that the database, apache and every config was in utf8.

PDO OBJECT

            $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.

USING str_word_count you need to use 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.

孤独难免 2024-12-17 22:11:22

UTF-8 问题与解决PHP 函数的解决方案

1。如何保存 UTF-8 Charterers(数学字符串,特殊字符,如 92 ÷ 8 ÷ 2 = ?)?

Ans. $string =utf8_encode('92 ÷ 8 ÷ 2 = ?');

2.如何从数据库打印 UTF-8 Charterers

echo utf8_decode($string);

注意:如果您不想使用编码/解码来执行此操作,您可以通过以下方式执行此操作:

1. 如果您使用 mysqli_query() 那么

$conn = mysqli_connect('localhost','db_username','password','your_database_name');
mysqli_set_charset($conn,"utf8"); 

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();

UTF-8 PROBLEMS & SOLUTIONS by PHP FUNCTIONS

1. How to Save UTF-8 Charterers (mathematical string,special chars like 92 ÷ 8 ÷ 2 = ? ) ?

Ans. $string =utf8_encode('92 ÷ 8 ÷ 2 = ?');

2. How to print UTF-8 Charterers From Database ?

Ans. echo 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

$conn = mysqli_connect('localhost','db_username','password','your_database_name');
mysqli_set_charset($conn,"utf8"); 

2.If you are using PDO then

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();
时光瘦了 2024-12-17 22:11:22

我只遇到了数据库结构中存储产品描述的文本字段的问题。我将字段设置设置为 blob 而不是文本,这解决了我的问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文