douping6871 2018-07-12 15:44
浏览 53
已采纳

在haystack中突出显示搜索到的char / string并保留大小写

At the moment I have programmed an ajax search which is returning names. So far everything is working. However, I want to highlight the searched char/string simply with a <strong> tag but keep the case as I have got it from the SQL:

Example:
Search Term: M
SQL result: 1. Max Mustermann, 2. Tom Maier

What I want:
<b>M</b>ax <b>M</b>uster<b>m</b>ann
Tom <b>M</b>aier

Means, I wanna keep the case as I get it from the database, just put tags around the char or string.

This is what I have so far, but it is not what I want. If I search a "m", the first char is also lower case although it is actually uppercase in the database.

public function highlightKeyword($haystack, $needle)
{
    $string = mb_strtolower($haystack);
    $string = $this->mb_ucfirst($string);
    $string = preg_replace("/(".$needle.")/i", sprintf("<strong>".strtolower($needle)."</strong>"), $string);
    return $string;
}

public function mb_ucfirst($string, $encoding)
{
    $strlen = mb_strlen($string, $encoding);
    $firstChar = mb_substr($string, 0, 1, $encoding);
    $then = mb_substr($string, 1, $strlen - 1, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $then;
}

Any further ideas?

  • 写回答

1条回答 默认 最新

  • douzou8074 2018-07-12 15:57
    关注

    Use preg_replace with /i (case-insensitivity flag) and a capture group:

    preg_replace('/('.preg_quote($needle).')/i', '<b>\1</b>', $haystack);
    

    The preg_quote is there to escape any reserved characters that might occur in the needle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊