Question

I have a test highlight function to highlight portions of a string in an autocomplete output. It works great, except it is case sensitive.

As you will see below the function doesn't work properly with $term = cer because the term is located at the beginning of the plant name where it is capitalized. If I change $term = can or $term = ercis all is well.

How could I make this function more dynamic and make it case-insensitive?

FUNCTION BELOW:

    <?php
    $term = 'cer';
    $termHighlight = '<span style="color:#cccccc">' . $term . '</span>';
    $plant = 'Cercis canadensis';

    $plant = str_replace($term, $termHighlight, $plant);
    print_r($plant);
    ?>

Thanks in advance amigos.

Was it helpful?

Solution

Well make use of str_ireplace() ! This is a case-insensitive version of your str_replace

$plant = str_ireplace($term, $termHighlight, $plant);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top