【问题标题】:php array contains not working in multi languagephp数组包含不能以多语言工作
【发布时间】:2025-12-11 17:30:02
【问题描述】:
$string = 'operating-system';
$array = array('operating-system');
$i = contains($array, $string);
echo ($i) ? "found ($i)" : "not found";

上面的代码打印 found(1)

$string = '운영체제';
$array = array('운영체제');
$i = contains($array, $string);
echo ($i) ? "found ($i)" : "not found";

但是这段代码打印出not found。为什么?

我已更新 charset=utf-8

function contains($needles, $haystack) {
        return count(array_intersect($needles, explode(" ", preg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
    }

【问题讨论】:

  • 请告诉我们contains的代码
  • @Rizier123:更新
  • 仅供参考:根据您的参数名称,您通常在 haystack 中搜索 needle,而不是相反 :)
  • 所以当我阅读您的代码时,您使用空格作为单词分隔符并想从字符串中搜索数组中有多少单词,

标签: php arrays utf-8 contains


【解决方案1】:

您需要一个支持多字节字符的本机函数。您可以使用mb_ereg_replace,而不是preg_replace

function contains($needles, $haystack) {
    return count(array_intersect($needles, explode(" ", mb_ereg_replace("/[^A-Za-z0-9' -]/", "", $haystack))));
}

您可能还想查看docs for all multibyte string functions

【讨论】: