看過簡單preg_replace(甚至只是str_replace)添加<span >搜索詞陣列的示例。但是很多搜索查詢會按照寫入的順序搜索術語:
搜索: blue shoes
MySQL查詢: SELECT * FROM my_table WHERE title LIKE '%blue%shoes%'
火柴:
MATCH- “別踩我的blue麂皮shoes”
NO MATCH - “...他的漂亮鞋子和他的淡藍色...”(關鍵字順序不正確)
MATCH-“blue shoes藍天下”(第二個“藍色”不應該突出顯示)
所以 SERP 應該以相同的方式突出匹配。是否有一種 REGEX 方法可以按順序使用n 個搜索詞來完成此操作?或者這是否需要以某種方式用 PHP 回圈處理?
錯誤的嘗試:
foreach ( ['blue', 'shoes'] as $term ) {
$result = str_replace($term, "<span style=\"background:yellow\">$term</span>", $title);
}
echo $result;
// This will highlight any instances of "blue" or "shoes" in any order in the result,
// even though the MySQL query searched for those terms in that specific order
uj5u.com熱心網友回復:
您必須使用 PHP 生成正則運算式模式:
function highlightMatches(array $searchTerms, string $string): string {
$result = $string;
foreach ($searchTerms as $i => $term) {
$previous = array_map(function($item) {
return "($item)";
}, array_slice($searchTerms, 0, $i 1));
$pattern = implode($previous, ". ");
$matches = [];
preg_match("/$pattern/", $string, $matches);
$lastMatch = array_pop($matches);
if ($lastMatch) {
$result = str_replace($lastMatch, "<span style=\"color: red;\">$lastMatch</span>", $result);
}
}
return $result;
}
$searchTerms = ["first", "second", "third"];
$strings = [
"first second third",
"third second first",
"second third first",
"third first second",
];
foreach ($strings as $str) {
echo $str . ":\t" . highlightMatches($searchTerms, $str) . "\n";
}
uj5u.com熱心網友回復:
您提到了 [mysql],所以我提出了可能與您在查找相關行時的要求非常接近的內容。
WHERE MATCH(col) AGAINST( "blue shoes" IN BOOLEAN MODE)
如果您的問題僅與 PHP 代碼有關,請洗掉 [mysql] 標記。
uj5u.com熱心網友回復:
implode()用于構建搜索模式和preg_replace()進行實際替換的另一個版本:
$haystacks = [
"Don't step on my blue suede shoes",
"... his fancy shoes and his baby blues...",
"blue shoes under the blue sky",
];
$needles = ['blue', 'shoes'];
$format = '<span style="background:red">%s</span>';
function highlightMatches($needles, $haystack, $format)
{
$search = '('.implode(')(. ?)(', $needles).')';
$replace = '';
$gaps_count = count($needles) - 1;
foreach ($needles as $k => $needle) {
$replace .= sprintf($format, '\\'.($k * 2 1));
if ($k < $gaps_count) {
$replace .= '\\'.($k *2 2);
}
}
return preg_replace("/$search/", $replace, $haystack);
}
foreach ($haystacks as $haystack) {
echo highlightMatches($needles, $haystack, $format)."<br>";
}
如果資料庫查詢可用于編輯,我會嘗試使用資料庫查詢進行突出顯示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350039.html
上一篇:php中按鍵重構多維json
