有特殊字母PHP字符串比较

问题描述 投票:-1回答:1

我有属性的数组,其使用REST API从woocommerce商店服用。看起来像:

Array
 (
 [0] => stdClass Object
    (
        [id] => 6
        [name] => Modelis
        [position] => 0
        [visible] => 1
        [variation] => 1
    )

[1] => stdClass Object
    (
        [id] => 5
        [name] => Krāsa
        [position] => 1
        [visible] => 1
        [variation] => 1
    )

)

在这阵我想名为“Krāsa”找项目。因为它含有特殊的字母“A”,简单的比较不工作:

foreach ($attributes as $item):
  if (!strcmp($item->name, 'Krāsa')):
    print_r('Names match');
  endif;
endforeach;

这样的if语句总是假的,虽然有名字Krāsa在数组中。也许这就是我可怜的背景,但我想知道,如何恰当地比较这些字符串?

非常感谢。

php arrays string string-comparison strcmp
1个回答
3
投票

在某些情况下,当你有你的字符串编码麻烦,您可以将您的字符串编码。

foreach ($attributes as $item):
    if (strcmp(mb_convert_encoding($item->name, 'utf-8', 'auto'), mb_convert_encoding('Krāsa', 'utf-8', 'auto')) == 0):
        print_r('Names match');
      endif;
    endforeach;
© www.soinside.com 2019 - 2024. All rights reserved.