Search code examples
phpiconvstrpos

Why use iconv_strpos instead of strpos?


In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. (Source: http://www.php.net/manual/en/function.iconv-strpos.php)

The following code example shows that iconv_strpos() and strpos() returning the same values.

$string = "dd.MM.yy";

echo "d: ".strpos($string, 'd'); // 0
echo "M: ".strpos($string, 'M'); // 3
echo "y: ".strpos($string, 'y'); // 6

echo "d: ".iconv_strpos($string, 'd'); // 0
echo "M: ".iconv_strpos($string, 'M'); // 3
echo "y: ".iconv_strpos($string, 'y'); // 6

Why should i use iconv_strpos instead of strpos?


Solution

  • It is usually only relevant when using multi-byte encodings such as UTF-8 or UTF-16.

    A character may consist of multiple bytes (this is the case for non-7-bit-ASCII characters in UTF-8 – these are variable in encoding length. UTF-16 has 2-byte characters).