很多人都问过如何在MySQL全文搜索结果中突出显示搜索词的问题,但我发现的解决方案似乎还不够。MySQL全文搜索支持引用的多词搜索目标,并忽略任何标点符号.因此,在我的搜索表单中,用户可以输入引用的术语"quick“,MySQL也将返回行,其中包括”快速,棕色“(例如),但不包括”快速和棕色“。因此,在突出显示返回文本中的搜索目标时,似乎需要执行一些正则表达式,以确保标识目标的所有实例。到目前为止,我看到的是,$targ包含一个可能包含多个单词的搜索词,比如“快速布朗”(但没有引号),而$blob是我们正在搜索的大型文本字符串。它的工作方式是将搜索目标中的任何空格替换为与任何非字母数字字符串匹配的正则表达式。
$pattern = '/' . str_replace(" ", '[^A-Za-z0-9\"]', $targ) . '/i';
$replacement = '<span class="hilite">' . $targ . '</span>';
$blob = preg_replace($pattern, $replacement, $blob);这主要是有效的,但有一个不幸的副作用。它实际上从整个字符串中删除了额外的标点符号。因此,如果$blob包含字符串“快速,棕色”,则将其更改为
<span class="hilite">quick brown</span>因此,它成功地在术语周围添加了span标记,但是在这个过程中,它删除了逗号。
我认为这个解决方案可能涉及到在通配符中使用preg_replace,但一个困难是$targ中可能包含不同数量的单词。
有什么建议吗?谢谢!
发布于 2015-07-30 06:09:57
通过捕获组,您可以很容易地做到这一点。另外,在接受用户输入的模式时,最好在使用它之前对其进行转义。
<?php
$source = 'quick, brown" (for example), but not "quick and brown". So whe';
$test = "QUICK BROWN";
$temp = explode(" ", $test);
// use preg_quote to escape the literal strings
$temp = array_map(function ($val) { return preg_quote($val, "~");}, $temp);
// stitch the literals together with the variable pattern
$pattern = '~('.implode("[^A-Za-z0-9]+", $temp).')~i';
// here the $1 means the result of the first capture group...
// capture group is denoted in the pattern as the text in ().
echo preg_replace( $pattern , '<span class="hilite">$1</span>', $source );您可以看到这个正在运行的这里。
https://stackoverflow.com/questions/31715664
复制相似问题