很多人问过如何在 MySQL 全文搜索结果中突出显示搜索词的问题,但我找到的解决方案似乎还不够。 MySQL 全文搜索支持引用的多单词搜索目标并忽略任何标点符号。因此,在我的搜索表单上,用户可以输入引用的术语“quick Brown”,MySQL 还将返回包含“quick,brown”(例如)的行,但不返回“quick and Brown”。因此,当在返回的文本中突出显示搜索目标时,似乎您需要执行一些正则表达式来确保识别目标的所有实例。到目前为止,我所拥有的是这样的,其中 $targ 包含可能的多字搜索词,例如“quick Brown”(但没有引号),而 $blob 是我们正在搜索的大字符串文本。它的工作原理是用与任何非字母数字字符串匹配的正则表达式替换搜索目标中的任何空格。
$pattern = '/' . str_replace(" ", '[^A-Za-z0-9\"]', $targ) . '/i';
$replacement = '<span class="hilite">' . $targ . '</span>';
$blob = preg_replace($pattern, $replacement, $blob);
这基本上有效,但有一个不幸的副作用。它实际上从完整字符串中删除了多余的标点符号。因此,如果 $blob 包含字符串“quick, Brown”,则会更改为
<span class="hilite">quick brown</span>
因此,它成功地在术语周围添加了 span 标签,但在此过程中,它删除了逗号。
我认为解决方案可能涉及使用带有通配符的 preg_replace,但一个困难是 $targ 中可能包含不同数量的单词。
有什么建议吗?谢谢!
最佳答案
您可以使用捕获组轻松地完成此操作。此外,当接受用户对模式的输入时,最好在使用它之前对其进行转义。
<?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 );
你可以看到这个正在运行 here .
关于PHP 突出显示 MySQL 全文搜索的多项结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31715664/