views:

148

answers:

3

If I search for tOm ArNfElD and the $variable is "Tom Arnfeld", I get great results form LIKE in MySQL (which is case-insensitive).

How could I wrap the matched text in the $variable with a <span></span> to highlight to what part of the search matched the query? I need to retain the original case of the $variable.

A: 

You can use str_ireplace() if you want to replace the whole string or convert your LIKE-parameter to a regular expression and use preg_replace() (don't forget to preg_quote() the string, though).

Example using regular expressions:

$parts = explode('%', $likeQuery)
foreach ($parts as &$innerString) {
    $innerParts = explode('_', $innerString);
    foreach ($innerParts as &$part) {
        $part = preg_quote($part, '/');
    }
    // always unset references when you're done with them
    unset($part):
    $innerString = implode('.', $innerString);
}
// always unset references when you're done with them
unset($innerString):
$regex = implode('.*?', $parts);
$transformedString = preg_replace("/$regex/", '<span>$0</span>', $stringToTransform);
soulmerge
A: 

I would use regular expressions:

$text = preg_replace('~(' . preg_quote($search, '~') . ')~i', '<span>$1</span>', $text);

There are other ways too, like the one soulmerge suggested (str_ireplace()):

$text = str_ireplace($search, '<span>' . $search . '</span>', $text);
Alix Axel
+1  A: 
$textToPrint = preg_replace("/({$variable})/i","<span class"myclass">$1</span>,$text);

this might help

andreas
grrr...someone else post it first while i was writing the answer
andreas
works perfectly!!
tarnfeld
@andreas: This is potentially bogus, you're not escaping (using `preg_quote()`) the `$variable`.
Alix Axel
@alix : it's just a tip - next time i will provide more detailed tips/solutions :)
andreas