PHP:类似搜索的单词突出显示
我正在为报纸应用程序开发一个简单的搜索引擎。当用户键入关键字时,会显示结果页面,并用颜色突出显示该术语。
我目前正在这样做:
$title = str_ireplace($term, "<span class='highlight'>$term</span>", $note->Title);
太好了,str_ireplace()
进行不区分大小写的搜索,但是当大小写与注释不匹配时(即用户查找“MONEY”并且注释显示“钱”),就会发生这种情况:
malvinas | Resultados de la búsqueda 1. malvinas: Argentina va a la ONU y Londres se enfurece » en Actualidad [...] Naciones Unidas, Ban-Ki Moon, ante quien reiterará que se cumplan las resoluciones de la ONU sobre el tema de la soberanía de las Islas [...]
注释的原始标题是“Malvinas:Argentina va a la ONU y Londres se enfurece”(不是“malvinas:”等)
如何在不更改原始单词的CaSe的情况下进行突出显示?
I'm working on a simple search engine for a newspaper application. When the user types a keyword, a results page is shown, highlighting the term with a color.
I'm currently doing this:
$title = str_ireplace($term, "<span class='highlight'>$term</span>", $note->Title);
Great, str_ireplace()
makes the case-insensitive search, but when the case doesn't match the note (i.e. the user looks for "MONEY" and the note says "money"), this happens:
malvinas | Resultados de la búsqueda 1. malvinas: Argentina va a la ONU y Londres se enfurece » en Actualidad [...] Naciones Unidas, Ban-Ki Moon, ante quien reiterará que se cumplan las resoluciones de la ONU sobre el tema de la soberanía de las Islas [...]
The original title of the note is "Malvinas: Argentina va a la ONU y Londres se enfurece" (not "malvinas: ", etc.)
How can I do a highlight without changing the original word's CaSe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用正则表达式:
输出:
Use regex:
Output:
您应该使用反向引用,并带有不区分大小写的修饰符。这样,当您替换该单词时,您将替换它本身(保持其大小写),而不是将其替换为搜索中使用的任何大小写。
将此方法与
preg_replace
结合使用将允许您传递一组搜索词以及每个搜索词的通用替换模式。You should use backreferences, with a case-insensitive modifier. That way when you replace the word, you are replacing it with itself (maintaining its case) and not replacing it with whatever the casing was that was used in the search.
Using this method with
preg_replace
will allow you to pass an array of search terms in, and a generic replacement-pattern for each.