strpos return wrong position at hebrew

2019-07-28 00:22发布

问题:

I need help... I have hebrew php string and I want search position of substring. my code:

$string = "אבגד הוזח טי";
$find = "הוזח";
$pos = strpos($string, $find);
echo $pos;

The strpos found the substring, but return wrong value of position. It return $pos value 9 Instead of 5. Why the strpos not working in hebrew strings? Can you help me please?

回答1:

Try using mb_strpos. You will have to set your internal character encoding to UTF-8 using mb_internal_encoding.

mb_internal_encoding("UTF-8");
$string = "אבגד הוזח טי";
$find = "הוזח";
$pos = mb_strpos($string, $find);
echo $pos; //5


回答2:

Hebrew strings use multibyte characters, so each "character" can be 2 or more characters long, and not 1, like most latin-based characters. You will probably want to look into PHP Multibyte String Functions for your application.