Search code examples
phpsearchstr-replacecapitalization

How to use str_replace without altering capitalization?


This is for a site search script. If I use str_ireplace, this will alter the capitalization of the search results. For example, if the query string is "search string" and a record containing "Search String" is found, the latter will lose its capitalization. Any way around this?

I need to incorporate highlighting for the search results.

The problem is not finding the string or getting it highlighted. I can use str_ireplace to accomplish this. But this will lose capitalization. What I want is to leave the capitalization intact, as well.


Solution

  • You could use preg_replace.

    $haystack = 'Some text here.';
    $str = preg_replace( "#(.*)(text)(.*)#i", '\1<b>\2</b>\3', $haystack );