Наконец-то я сделал рабочий раствор.Отправьте ответ, если кто-то ответит на тот же вопрос.
class Highlighter
{
private $_text;
private $_keywords;
private $keywords;
private $text;
private $tag = "b";
public function highlight($text, $keywords)
{
$this->text = $text;
$this->keywords = (array) $keywords;
if(count($keywords) > 0)
{
$this->prepareString();
$this->highlightStrings();
}
return $this->text;
}
private function unicodeSymbols()
{
return [
'ā' => 'a',
'č' => 'c',
'ē' => 'e',
'ī' => 'i',
'ķ' => 'k',
'ļ' => 'l',
'ņ' => 'n',
'š' => 's',
'ū' => 'u',
'ž' => 'z'
];
}
private function clearVars()
{
$this->_text = null;
$this->_keywords = [];
}
private function prepareString()
{
$this->clearVars();
$this->_text = strtolower( strtr($this->text, $this->unicodeSymbols()) );
foreach ($this->keywords as $keyword)
{
$this->_keywords[] = strtolower( strtr($keyword, $this->unicodeSymbols()) );
}
}
private function highlightStrings()
{
foreach ($this->_keywords as $keyword)
{
if(strlen($keyword) === 0) continue;
// find cleared keyword in cleared text.
$pos = strpos($this->_text, $keyword);
if($pos !== false)
{
$keywordLength = strlen($keyword);
// find original keyword.
$originalKeyword = mb_substr($this->text, $pos, $keywordLength);
// highlight in both texts.
$this->text = str_replace($originalKeyword, "<{$this->tag}>".$originalKeyword."</{$this->tag}>", $this->text);
$this->_text = str_replace($keyword, "<{$this->tag}>".$keyword."</{$this->tag}>", $this->_text);
}
}
}
public function setTag($tag)
{
$this->tag = $tag;
}
}