drwo32555 2016-11-19 00:48
浏览 113
已采纳

语法突出显示,使用不区分大小写的语法

I am trying to write a search and syntax highlighter. Let's presume we have a basic query, that is querying for countries based on a keyword, for example uni.

Right now, I am using Sphinx, to fetch the results that match with this keyword from a database, and I am using case-insensitive search. The results that sphinx return are the following:

Tanzania, United Republic of
United Arab Emirates
United Kingdom
United States
Igaunija
Estados unidos Mexicanos

I now want to highlight the search keyword from these strings, by wrapping the keyword in a <span>.

To achieve this, I was trying to do the following:

$search='uni';
foreach($keyword as $text) { // $keyword is an array, containg each found result one by one
  $text=str_replace($search, "<span>".$search."</span>", $text);
}

Whit this code, only Iguanija, and Estados unidos Mexicanos gets highlighted, because in every other case the keyword starts with an uppercase letter. If I change the str_replace to a str_ireplace, every search keyword get's highlighted, but in the first few entries, the uppercase U gets replaced with a lowercase u, so from United Kingdom, I get united Kingdom. How could I highlight the search keyword, and maintain the case of the characters in the result?

My desired result would be something like this:

Tanzania, <span>Uni</span>ted Republic of
<span>Uni</span>ted Arab Emirates
<span>Uni</span>ted Kingdom
<span>Uni</span>ted States
Iga<span>uni</span>ja
Estados <span>uni</span>dos Mexicanos
  • 写回答

1条回答 默认 最新

  • doushi7819 2016-11-19 00:57
    关注

    You can use a regular expression which will allow you to preserve the case of the source string.

    <?php
    
    $unis = <<< UNIS
    Tanzania, United Republic of
    United Arab Emirates
    United Kingdom
    United States
    Igaunija
    Estados unidos Mexicanos
    UNIS;
    
    var_dump(preg_replace('/(uni)/i','<span>$1</span>',$unis));
    

    Output

    string(190) "Tanzania, <span>Uni</span>ted Republic of
    <span>Uni</span>ted Arab Emirates <span>Uni</span>ted Kingdom
    <span>Uni</span>ted States Iga<span>uni</span>ja Estados
    <span>uni</span>dos Mexicanos"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)