突出显示匹配的关键字,不带重音字母


Highlight matched keywords without accented letter

我已将此代码应用于我的搜索功能。它目前工作得很好。但是,如果我输入的关键字没有重音字母,它将不会突出显示该单词。

例: $text ="iPhone Mới"

如果我输入关键字"moi",它不会突出显示$text中的单词"mới"。我也尝试了模式中的 u 标志作为谷歌的建议,但它也没有奏效。请帮忙...

这是我的代码:

<?php
function highlightWords($text, $words)
{
/*** loop of the array of words ***/
foreach ($words as $word)
{
        /*** quote the text for regex ***/
        $word = preg_quote($word);
        /*** highlight the words ***/
        $text = preg_replace("/($word)/ui", '<span class="highlight_word">'1</span>', $text);
}
/*** return the text ***/
return $text;
}

/*** example usage ***/
$text = 'this is my iphone mới';
/*** an array of words to highlight ***/
$words = array('moi');
/*** highlight the words ***/
$highlighttext =  highlightWords($string, $words);
?>
<html>
<head>
<title>PHPRO Highlight Search Words</title>
<style type="text/css">
.highlight_word{
background-color: pink;
}
</style>
</head>
<body>
 <?php echo $highlighttext; ?>

您可以使用以下代码:

setlocale(LC_ALL, 'en_US');
$word = iconv("utf-8","ascii//TRANSLIT",$word);
/*** quote the text for regex ***/

这将从$word中删除所有变音符号。

然后,您可以循环访问每个字符并将其替换为字符类(如果该字符具有替代形式)。例如,o变得[ớọơờớòo] .

注意:nhahtdh提出了一个很好的观点。我不知道这些变音符号来自什么语言,更不用说是否有任何字符应该成为具有不同变音符号的字符了。

如果您想按照这条线执行某些操作,请不要扁平化$word并为重音字符添加规则,例如:ơ变得[ờớơ]