Reputation: 26556
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
.
Upvotes: 3
Views: 671
Reputation: 75714
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);
Upvotes: 0
Reputation: 5335
$textToPrint = preg_replace("/({$variable})/i","<span class"myclass">$1</span>,$text);
this might help
Upvotes: 1
Reputation: 154553
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);
Upvotes: 1