如何在 PHP 中检测 pensé 与 pense 相同

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

如何在 PHP 中进行测试来比较两个单词(一个带有重音符号)并检测是否是同一个单词?

例如

pensé
vs
pense

基本上我告诉它从 MySQL 表中加载某些单词,并且通过 MySQL 排序规则设置,它从数据库加载两个版本,这很好,但我希望 PHP 也将它们检测为同一个单词(就像 MySQL 在这种特殊情况下所做的那样) .

我认为在 PHP 中可以使用 collator 类来完成,但我不明白它是如何工作的。

php encoding utf-8 collation diacritics
1个回答
0
投票

正如您所提到的,您可以使用 PHP

Collator
类。

Collator
是 intl 扩展的一部分 - 确保您的 PHP 启用了 intl 扩展

<?php
// Check if Intl extension is loaded
if (!extension_loaded('intl')) {
    exit('Intl extension is not enabled. Please enable it to use Collator.');
}

// Create a Collator object with a specific locale
$collator = new Collator('en_US');

// Set the strength to PRIMARY to ignore accents and case differences
$collator->setStrength(Collator::PRIMARY);

// Strings to compare
$string1 = 'pensé';
$string2 = 'pense';

// Compare the strings
if ($collator->compare($string1, $string2) == 0) {
    echo "The strings are considered equal.";
} else {
    echo "The strings are not equal.";
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.