Output Search Results PHP Script

So, let's say I'm doing a search on my site for "Tales of an Ancient Empire". My database does a full text search and the results appear. I have this function to highlight thngy

function sublinhamos($text, $words) { // explode the phrase in words $wordsArray = explode(' ', $words); // loop all searched words foreach($wordsArray as $word) { //highlight $text = str_ireplace($word, "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count); } //right trows results return $text; } 

This is not so bad, but the problem here is that the terms seach are β€œTales of the Ancient Empire”, when str_ireplace finds an already inserted SPAN, it encounters β€œa” words from the search term and breaks the SPAN tag.

I need highlighting to highlight parts of a word, and all words up to two characters are minimal, but all this is different from the old problem with the SPAN problem.

Any ideas please?

+4
source share
4 answers

Well, for starters, I would not use span.

 <mark></mark> 

is the best item to use. It is intended to highlight parts of the text like this. See this article for more details.

Alternatively, you can pass the array to str_replace, for example:

 function sublinhamos($text, $words) { $wordsArray = array(); $markedWords = array(); // explode the phrase in words $wordsArray = explode(' ', $words); foreach ($wordsArray as $k => $word) { $markedWords[$k]='<mark>'.$word.'</mark>'; } $text = str_ireplace($wordsArray, $markedWords, $text); //right trows results return $text; } 
+5
source

Instead, you can replace it with a temporary string that will not search (for example, {{{and}}} as follows:

 $text = str_ireplace($word, "{{{".strtoupper($word)."}}}", $text, $count); 

After marking all of your hits, you can simply replace the temporary lines with span tags

+1
source

Instead, you can use preg_replace with a negative appearance:

 $text = preg_replace('/(?<!<sp)(?<!<\/sp)(an)/i', '<span class="highlight">$1</span>', $text); 

The first appearance is the launch of span tags, and the second is to complete the tags. Perhaps you can combine them into one, but not sure.

0
source

Have you tried something like this?

 $text = preg_replace("|($word)|", "<span class=\"highlight\">".strtoupper($word)."</span>", $text, $count); 
0
source

Source: https://habr.com/ru/post/1386488/


All Articles