Adam Baranyai Adam Baranyai - 16 days ago 9
PHP Question

Syntax highlighting, with case insensitive syntax

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

Answer

You can use a regular expression which will allow you to preserve the case of the source string.

<?php

$unis = <<< UNIS
Tanzania, United Republic of
United Arab Emirates
United Kingdom
United States
Igaunija
Estados unidos Mexicanos
UNIS;

var_dump(preg_replace('/(uni)/i','<span>$1</span>',$unis));

Output

string(190) "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"
Comments