Search code examples
phpstringtextreplaceword-wrap

Retain case when using str_ireplace?


I am building a search that will wrap the searched text with a <span> tag and I have this code working OK:

str_ireplace($q,'<span>'.$q.'</span>',$row[name]);

The problem is, if a user searches for Tom is will show Tom which is cool, but if they put in tom because of the str_ireplace it would show tom, does that make sense? The real issue is if someone entered tOm aRnFeLd although it would search OK, the aesthetics would actually show up on the page tOm aRnFeLd

How can I retain the capital letters and lower case 'ness of both strings? Is there a better way to wrap case insensitive text from a string?


Solution

  • use stristr to get the needle from the haystack, case insensitive

    $keyword_caseRetained_all = stristr($excerpt, $keyword);
    

    but that returns the needle and the rest of haystack too, so you have to use substr to only keep the needle portion. start at position 0, get up to the length of keyword

    $keyword_caseRetained = substr($keyword_caseRetained_all, 0, strlen($keyword) );
    

    now use that variable inside the str_ireplace function

    $excerpt = str_ireplace($keyword, '<em>'.$keyword_caseRetained.'</em>', $excerpt);
    

    once you know this, you can combine lines 1 and 2 in a nice rats nest to shorten your code.

    or add this as a method to a string manipulation class.