I'm trying to program a search function that hightlights the search query in the result. At the moment I'm using this Code $hightlight = preg_replace('/'.strtolower($query).'/', '<span class=hightlight>'.strtolower($query).'</span>', strtolower($text));
for highlighting, which works fine. The text I'm searching in is a string from a database. The problem now is if the text contains some html special characters, and is for example <test>
and the user searches for <te
I get the following result: <span class="hightlight"><te< span="">st></te<></span>
which is interpretated as st>
. This makes sense, but I don't want this. I want <test>
as result with <te
highlighted. So I need to escape the special characters. I know that there is the function htmlspecialchars
, but how can I use it in this case? Or another function? I can't escape them before searching, because than I'm also searching in the HTML-Codes. I also can't escape them after searching, because than are the <span>
Tags in the text and they will also be converted to HTML-Codes. I hope you understand my problem. Has anyone a solution for that?
PHP突出显示查询和转义html特殊字符
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- doubu4406 2017-10-13 14:19关注
Using a combination of
htmlspecialchars()
and a regex negative lookahead, I think we're able to solve this.<php $text = "this is just my really basic <test> of words"; $query = "<te"; $text = htmlspecialchars($text); $query = htmlspecialchars($query); $highlight = preg_replace('/'.strtolower($query).'(?![^\&]*\;)/', '<span class=highlight>'.strtolower($query).'</span>', strtolower($text)); echo $highlight; ?>
(small note, I took the liberty of changing
hightlight
tohighlight
)The part of this that solves the issue mentioned in your comment is the negative lookahead:
(?![^\&]*\;)
That basically means anything not between
&
and;
.Now, this could obviously run into issues in some edge cases where
&
and;
are both part of the actual text. If you're not doing any sort of text and query limitation/sanitation, I'm not sure that there's anything that will work for all possible cases.本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥40 复杂的限制性的商函数处理
- ¥15 程序不包含适用于入口点的静态Main方法
- ¥15 素材场景中光线烘焙后灯光失效
- ¥15 请教一下各位,为什么我这个没有实现模拟点击
- ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
- ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
- ¥20 有关区间dp的问题求解
- ¥15 多电路系统共用电源的串扰问题
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码