代码之家  ›  专栏  ›  技术社区  ›  ali

比较字符串和中间点在PHP中不起作用

  •  1
  • ali  · 技术社区  · 9 年前

    我从数据库中得到一个字符串,在那里用 utf8_unicode_ci 。它可能包含 中间点字符 ()我必须找出使用 strcmp 。如果我直接在HTML中显示字符串,字符将毫无问题地显示出来,但当我进行比较时,结果并不是我所期望的。

    例如:

    $string = "⋅⋅⋅ This string starts with middle dots";
    $result = strcmp(substr($string , 0, 2), "⋅⋅");
    

    2 回复  |  直到 9 年前
        1
  •  2
  •   Dave Chen    9 年前

    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);
    
        2
  •  2
  •   treyBake user1850175    9 年前

    strpos - http://uk1.php.net/manual/en/function.strpos.php

    这将返回指定字符第一次出现的int值。例如。:

    $myStr = '.. this is a string';
    $find  = '..';
    $pos   = strpos($myStr, $find);
    
    var_dump($pos); //will output 0;