سؤال

I use this code to search for one utf-8 string in another utf-8 string:

if (strlen(mb_stristr($string1, $string2)) > 0)

but it always returns 0! Does anyone know any better solution to this problem? Both strings may be some combination of unicode and non-unicode characteres!

هل كانت مفيدة؟

المحلول

If you're not using the substring, don't use strstr (or its derivitives). All you care about is that the string exists, so use mb_stripos:

if (mb_stripos($string1, $string2) !== false) {

نصائح أخرى

Why not just use mb_stripos?

If you don't know the source encoding(s) you may need to use mb_detect_encoding and subsequently mb_convert_encoding to convert each of the strings into a common encoding, but this should be fairly trivial.

That said, you need to check for false in case string2 occurs at the start (i.e.: position zero) of string1.)

i.e.: Use...

if (mb_stripos($string1, $string2) !== false) {
    // $string2 was found within $string1
    ...
}
if (mb_stristr($string1, $string2) !== false) echo "found $string2 in $string2";

Note the type safe comparison operator !==.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top