在给定字符串utf-8上设置特定单词样式的函数?

function to style specific words on a given string utf-8?

如何设置给定字符串中特定单词的样式? 我使用了一个函数来设置给定字符串中特定单词的样式,但这在 utf-8 字符串

中不起作用
 header('Content-type: text/html; charset=utf-8');
function bold($string, $word)
{
    return preg_replace('/\b'.$word.'\b/', '<strong>'.$word.'</strong>', $string);
}

echo bold('چمستان تا', 'تا');

我该怎么做?我需要根据键入的用户查询在搜索结果中加粗一些关键字/短语

如有任何帮助,我们将不胜感激

确保:

  • 您的页面以 UTF8 编码保存
  • 添加/u修饰符
  • 更好preg_quote搜索词以防万一

使用

preg_replace('/\b'.preg_quote($word,'/').'\b/u', '<strong>'.$word.'</strong>', $string);

作为 \b 的替代方法,您可以使用无歧义的词边界(不允许在搜索词之前或之后使用词字符):

preg_replace('/(?<!\w)'.preg_quote($word,'/').'(?!\w)/u', '<strong>'.$word.'</strong>', $string);

或 - 在空格内强制匹配:

preg_replace('/(?<!\S)'.preg_quote($word,'/').'(?!\S)/u', '<strong>'.$word.'</strong>', $string);