比较带有中间点的字符串在 PHP 中不起作用
Compare strings with middle dot not working in PHP
我从数据库中得到一个字符串,它是用 utf8_unicode_ci
编码的。它可能包含 中点字符 (⋅),我必须使用 strcmp
找出答案。如果我直接显示 HTML 中的字符串,字符显示没有问题,但是当我进行比较时,结果不是我所期望的。
例如:
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(substr($string , 0, 2), "⋅⋅");
结果不是0,我认为应该是。 PHP 文件以 UTF-8 编码保存。我在这里错过了什么?即使我从变量而不是数据库中获取字符串,也会发生这种情况
使用 strpos
- http://uk1.php.net/manual/en/function.strpos.php
this returns 指定字符第一次出现的 int 值。例如:
$myStr = '.. this is a string';
$find = '..';
$pos = strpos($myStr, $find);
var_dump($pos); //will output 0;
如果找不到 - 它 returns 错误。
PHP的substr不把unicode字符当成单个字符
dot you're using实际上是3个字符,0xE2 0x8B 0x85
.
所以要么使用 mb_substr,要么使用不同的偏移量:
<?php
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(mb_substr($string , 0, 2), "⋅⋅");
var_dump($result);
或者如果 mb_* 函数不存在:
<?php
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(substr($string , 0, 6), "⋅⋅");
var_dump($result);
我从数据库中得到一个字符串,它是用 utf8_unicode_ci
编码的。它可能包含 中点字符 (⋅),我必须使用 strcmp
找出答案。如果我直接显示 HTML 中的字符串,字符显示没有问题,但是当我进行比较时,结果不是我所期望的。
例如:
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(substr($string , 0, 2), "⋅⋅");
结果不是0,我认为应该是。 PHP 文件以 UTF-8 编码保存。我在这里错过了什么?即使我从变量而不是数据库中获取字符串,也会发生这种情况
使用 strpos
- http://uk1.php.net/manual/en/function.strpos.php
this returns 指定字符第一次出现的 int 值。例如:
$myStr = '.. this is a string';
$find = '..';
$pos = strpos($myStr, $find);
var_dump($pos); //will output 0;
如果找不到 - 它 returns 错误。
PHP的substr不把unicode字符当成单个字符
dot you're using实际上是3个字符,0xE2 0x8B 0x85
.
所以要么使用 mb_substr,要么使用不同的偏移量:
<?php
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(mb_substr($string , 0, 2), "⋅⋅");
var_dump($result);
或者如果 mb_* 函数不存在:
<?php
$string = "⋅⋅⋅ This string starts with middle dots";
$result = strcmp(substr($string , 0, 6), "⋅⋅");
var_dump($result);