Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use mb_strpos(); over strpos();?

Tags:

string

php

strpos

Huh, looking at all those string functions, sometimes I get confused. One is using all the time mb_ functions, the other - plain ones, so the question is simple...

When should I use mb_strpos(); and when should I go with the plain one (strpos();)?

And, yes, I'm aware about that mb_ functions stand for multi-byte, but does it really mean, that if I'm working with only utf-8 encoded strings, I should stick with mb_ functions?

Thanks in advance!

like image 814
tomsseisums Avatar asked Dec 08 '25 10:12

tomsseisums


2 Answers

You should use the mb_ functions whenever you expect to work with text that's not pure ASCII. I.e. you can work with the regular string functions, even if you're using UTF-8, as long as all the strings you're using them on only contain ASCII characters.

strpos('foobar', 'foo')  // fine in any (ASCII-compatible) encoding, including UTF-8
strpos('ふーばー', 'ふー') // won't work as expected, use mb_strpos instead
like image 170
deceze Avatar answered Dec 09 '25 23:12

deceze


Yes, if working with UTF-8 (which is a multi-byte encoding : one character can use more than one byte), you should use the mb_* functions.

The non-mb functions will work on bytes, and not characters -- which is fine when 1 character == 1 byte ; but that's not the case with (for example) UTF-8.

like image 30
Pascal MARTIN Avatar answered Dec 10 '25 00:12

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!