Text wrap - case insensitive with php

If I search tOm ArNfElD, and $variable- "Tom Arnfeld", I get an excellent form of results LIKEin MySQL (which is not case sensitive).

How can I wrap matching text in $variablewith <span></span>to highlight in which part of the search the query matches? I need to keep the original case $variable.

+3
source share
3 answers
$textToPrint = preg_replace("/({$variable})/i","<span class"myclass">$1</span>,$text);

this can help

+1
source

I would use regular expressions:

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

There are other ways, for example, soulmerge ( str_ireplace()):

$text = str_ireplace($search, '<span>' . $search . '</span>', $text);
+1
source

str_ireplace(), LIKE- preg_replace() ( preg_quote() , ).

:

$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);
0

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


All Articles