开发者

Issue with string comparison in PHP

I have two strings with seemingly the same values. One is stored as a key in an array, the other a value in another different array. I comp开发者_JAVA技巧are the two using ==, ===, and strcmp. All treat them as different strings. I do a var_dump and this is what I get.

string(17) "Valentine’s Day" 
string(15) "Valentine's Day"

Does anyone have any idea why the first string would be 17 characters and the second 15?

Update: This is slightly more obvious when I pasted this out of my editor whose font made the two different apostrophe's almost indistinguishable.


The first string contains a Unicode character for the apostrophe while the second string just has a regular ASCII ' character.

The Unicode character takes up more space.

If you run the PHP ord() function on each of those characters you'll see that you get different values for each:

echo ord("’"); //226 This is just the first 2 bytes (see comments below for details from ircmaxell)
echo ord("'"); //27


As a complement to @Mark answer above which is right (the is a multi-byte character, most probably UTF-8, while ' is not). You can easily convert it to ASCII (or ISO-8859-1) using iconv, per example:

echo iconv('utf-8', 'ascii//TRANSLIT', $str);

Note: Not all characters can be transformed from multi-byte to ASCII or latin1. You can use //IGNORE to have them removed from the resulting string.


’ != '

mainly. if you want this not to be an issue, you could do something like this.

if (str_replace('’', '\'', "Valentine’s Day") == "Valentine's Day") {

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜