I am trying to write a search and syntax highlighter. Let's presume we have a basic query, that is querying for countries based on a keyword, for example uni.
Right now, I am using Sphinx, to fetch the results that match with this keyword from a database, and I am using case-insensitive search. The results that sphinx return are the following:
Tanzania, United Republic of
United Arab Emirates
United Kingdom
United States
Igaunija
Estados unidos Mexicanos
I now want to highlight the search keyword from these strings, by wrapping the keyword in a <span>
.
To achieve this, I was trying to do the following:
$search='uni';
foreach($keyword as $text) { // $keyword is an array, containg each found result one by one
$text=str_replace($search, "<span>".$search."</span>", $text);
}
Whit this code, only Iguanija
, and Estados unidos Mexicanos
gets highlighted, because in every other case the keyword starts with an uppercase letter. If I change the str_replace
to a str_ireplace
, every search keyword get's highlighted, but in the first few entries, the uppercase U
gets replaced with a lowercase u
, so from United Kingdom
, I get united Kingdom
. How could I highlight the search keyword, and maintain the case of the characters in the result?
My desired result would be something like this:
Tanzania, <span>Uni</span>ted Republic of
<span>Uni</span>ted Arab Emirates
<span>Uni</span>ted Kingdom
<span>Uni</span>ted States
Iga<span>uni</span>ja
Estados <span>uni</span>dos Mexicanos