你好,我有一个搜索功能,我将在数据库中搜索关键字。我想突出显示关键字并找到我想在搜索功能中实现的第二个功能。
所以我有这个搜索代码:
<?php
function searchText($keywords){
global $db;
$returned_results = array();
$where2 = "";
$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach ($keywords as $key=>$keyword){
$where2 .= "`column` LIKE '%$keyword%'";
if ($key != ($total_keywords - 1)){
$where2 .= " OR ";
}
}
$results_text = "SELECT `a`, `b`, LEFT(`c`, 150) as `c` FROM `table` WHERE $where2";
$results_num_text = ($query2 = mysqli_query($db, $results_text)) ? mysqli_num_rows($query2) : 0;
if ($results_num_text === 0){
return false;
} else {
while ($row = mysqli_fetch_assoc($query2)){
$returned_results[] = array(
'ab' => $row['ab'],
'cd' => $row['cd'],
);
}
return $returned_results;
}
}
?>
并希望在其中实现第二个功能:
<?php
function mark_words ($text, $words, $colors = false)
{
if (!$colors || !is_array($colors) ) {
$colors = array('#ff9999', '#ffff99', '#ff99ff', '#99ffff','#99ff99');
}
$c = 0;
foreach ($words as $w) {
$w = preg_quote(trim($w));
if($w=='') {
continue;
}
$regexp = "/($w)(?![^<]+>)/i";
$replacement = '<b style="background-color:'.$colors[$c].'">\\1</b>';
$text = preg_replace ($regexp,$replacement ,$text);
$c++;
if ($c >= count($colors)) {
$c=0;
}
}
return $text;
}
$example = <<< EOT
some text is here inside
EOT;
$search = array('some','is', 'inside');
echo mark_words($example, $search);
?>
所以我有这个不起作用的代码:
<?php
function searchText($keywords, $colors = false){
global $db;
if (!$colors || !is_array($colors) ) {
$colors = array('#ff9999', '#ffff99', '#ff99ff', '#99ffff','#99ff99');
}
$c = 0;
$returned_results = array();
$where2 = "";
$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach ($keywords as $key=>$keyword){
$regexp = "/($w)(?![^<]+>)/i";
$replacement = '<b style="background-color:'.$colors[$c].'">\\1</b>';
$text = preg_replace($regexp,$replacement ,$keywords);
$c++;
if ($c >= count($colors)) {
$c=0;
}
$where2 .= "`b` LIKE '%$keyword%'";
if ($key != ($total_keywords - 1)){
$where2 .= " OR ";
}
}
$results_text = "SELECT `a`, LEFT(`b`, 150) as `b`, `c` FROM `table` WHERE $where2";
$results_num_text = ($query2 = mysqli_query($db, $results_text)) ? mysqli_num_rows($query2) : 0;
if ($results_num_text === 0){
return false;
} else {
while ($row = mysqli_fetch_assoc($query2)){
$returned_results[] = array(
'ab' => $row['a'],
'cd' => $row['b'],
);
}
return $returned_results;
$highlight = array($keywords);
echo mark_words($highlight);
}
}
?>
当我寻找它时,我发现了两种可能性。第一个是一个函数,第二个是直接从选择查询中突出显示它:
SELECT
REPLACE(`col`, 'foobar', '<span class="highlight">foobar</span>') AS `formated_foobar`
FROM
…
WHERE
`col` LIKE "%foobar%"
所以我的问题是如何将第二个功能实现到搜索功能中,还是使用第二种方法更好?
如果有人可以帮助我,我将不胜感激。多谢。