PHP 带特殊字母的字符串比较
PHP string comparison with special letters
我有一组属性,使用 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' 的项目。由于它包含特殊字母'ā',简单比较不起作用:
foreach ($attributes as $item):
if (!strcmp($item->name, 'Krāsa')):
print_r('Names match');
endif;
endforeach;
即使数组中有名称 Krāsa,这样的 if 子句始终为 false。也许这是我的背景不佳,但我想知道,如何正确比较这样的字符串?
非常感谢。
在某些情况下,当您在字符串编码方面遇到问题时,您可以转换字符串编码。
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;
我有一组属性,使用 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' 的项目。由于它包含特殊字母'ā',简单比较不起作用:
foreach ($attributes as $item):
if (!strcmp($item->name, 'Krāsa')):
print_r('Names match');
endif;
endforeach;
即使数组中有名称 Krāsa,这样的 if 子句始终为 false。也许这是我的背景不佳,但我想知道,如何正确比较这样的字符串?
非常感谢。
在某些情况下,当您在字符串编码方面遇到问题时,您可以转换字符串编码。
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;