Search code examples
phppreg-replacematchcase-insensitive

case insensitive preg replace on special chars/Umlaute


This works:

echo preg_replace("/TesT/i","<b>FOUND</b>","TEST"); // works as expected prints FOUND

Why does this below not work? In my project I want to highlight a search result no matter of the case/writing of the search input

echo preg_replace("/üöÄ/i","<b>FOUND</b>","ÜÖÄ"); // does NOT work as expected prints ÜÖÄ 

I tried the below as well which also does not work:

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");
mb_ereg_replace("/üöÄ/i","<b>FOUND</b>","ÜÖÄ");

UPDATE:
As far as I know I made sure everything on my page, the scripts, the connections are all UTF-8


Solution

  • You additionally need to pass the u option for utf8 support.

    This will work:

    echo preg_replace("/üöÄ/iu","<b>FOUND</b>","ÜÖÄ");
    

    You can find the list of available options here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php