CodexBloom - Programming Q&A Platform

PHP 8.1 how to to Use str_contains with Multibyte Characters in UTF-8 Strings

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
php utf-8 str_contains PHP

I'm wondering if anyone has experience with I've been struggling with this for a few days now and could really use some help... I'm currently developing a web application using PHP 8.1 and I've run into a question with the `str_contains` function when dealing with multibyte UTF-8 characters. My code looks like this: ```php $haystack = 'γ“γ‚“γ«γ‘γ―δΈ–η•Œ'; // 'Hello World' in Japanese $needle = 'δΈ–η•Œ'; // 'World' if (str_contains($haystack, $needle)) { echo 'Found!'; } else { echo 'Not Found!'; } ``` I expected the output to be 'Found!', but instead, it returns 'Not Found!'. After checking the value of `$haystack` and `$needle`, they both appear to be correct and I verified that `$haystack` is indeed a UTF-8 encoded string. I've also tried using `mb_strpos` as follows: ```php if (mb_strpos($haystack, $needle) !== false) { echo 'Found!'; } else { echo 'Not Found!'; } ``` This gives me the expected result, but I would prefer sticking with `str_contains` for its simplicity. Is there a limitation of `str_contains` when it comes to multibyte characters, or is there something that I'm missing in the way I'm using it? Any insights would be greatly appreciated. This is part of a larger API I'm building. I'd really appreciate any guidance on this.