用与MySQL相同的方式比较PHP中的字符串 [英] Comparing strings in PHP the same way MySQL does

查看:138
本文介绍了用与MySQL相同的方式比较PHP中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将varchar存储在utf8 MySQL表中,并使用utf8_general_ci排序规则.我在varchar上有一个唯一索引.我想在PHP中做一个字符串比较,它等同于MySQL在索引上所做的事情.

I'm storing a varchar in a utf8 MySQL table and using utf8_general_ci collation. I have a unique index on the varchar. I'd like to do a string comparison in PHP that is equivalent to what MySQL will do on the index.

一个具体的例子是,我希望能够在这种情况发生之前检测出'a'在PHP中被认为等同于'À':

A specific example is that I'd like to be able to detect that 'a' is considered equivalent to 'À' in PHP before this happens:

mysql> insert UniTest (str) values ('a');                                   
Query OK, 1 row affected (0.00 sec)

mysql> insert UniTest (str) values ('À');                                   
ERROR 1062 (23000): Duplicate entry 'À' for key 1

推荐答案

排序规则与存储无关.您需要设置字符集以确定存储编码.排序规则控制比较和排序的方式.排序规则必须能够识别字符集,否则它与字符集无关.

The collation has nothing to do with the storage. You need to set the charset to determine the storage encoding. The collation governs how comparison and sorting should happen. The collation must be charset aware, but otherwise it has nothing to do with the charset.

要回答您的问题,可以使用iconv传送文本,然后进行比较.例如:

To answer your question, you can use iconv to translitter the text, and then compare it. For example:

function compare($s1, $s2) {
  return strcmp(
    iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s1),
    iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $s2));
}

这基本上是MySql将为您执行的操作,尽管它可能更快,并且排序表可能与ISO-8859-1//TRANSLIT略有不同.对此不完全确定.

This is basically what MySql will do for you, although it's probably faster and it may have a slightly different collation-table than ISO-8859-1//TRANSLIT. Not entirely sure about that.

但是,正如其他人已经建议的那样,使用数据库可能会更容易.

Would probably be easier to use the database though, as others have already suggested.

这篇关于用与MySQL相同的方式比较PHP中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆