【问题标题】:function to style specific words on a given string utf-8?在给定字符串 utf-8 上设置特定单词样式的函数?
【发布时间】:2025-12-18 04:50:01
【问题描述】:

如何为给定字符串中的特定单词设置样式? 我有一个函数来设置给定字符串中特定单词的样式,但这在 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('چمستان تا', 'تا');

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

任何帮助将不胜感激

【问题讨论】:

  • 试试'/\b'.$word.'\b/u'
  • 错误:警告:preg_replace():编译失败:偏移 2 处的 UTF-8 字符串无效
  • 您确定您的文件是以utf-8 编码保存的吗?
  • 那就试试'/(?&lt;!\w)' . preg_quote($word,'/') . '(?!\w)/u'
  • 在使用 utf-8 保存后,我的页面没有使用 ANSI 保存,您的正则表达式有效,谢谢

标签: php utf-8 preg-replace


【解决方案1】:

确保:

  • 您的网页使用 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);

【讨论】:

  • 函数粗体($string, $word) { return preg_replace('/(?'.$word.'', $string); } 回声粗体(“你好世界”,“你好我”);为什么这不起作用,但是当我删除“wo”时,它起作用了
  • 它不起作用,因为hello wowo 之后需要一个空格或字符串结尾。 hello world 中没有空格或字符串结尾。见ideone.com/CGX8Pa
  • 当我在 google 中搜索一个单词时,我在 google 搜索结果中以粗体显示的单词你能为我创建一个类似 google 的功能吗?
  • 我没有回答你的问题吗?是关于重新创建 Google 的问题吗?
  • 不,谢谢您的回答。我不想重新创建谷歌只是我不能说英语而且我不能问我的问题