Question

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?

Was it helpful?

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).

OTHER TIPS

When you are using multibyte encodings a single character can be represented by a variable number of bytes (e.g. in UTF-8 from 1 to 4). This is in contrast to single-byte encodings, where each byte always represents exactly one character.

Consider a two-char string encoded in UTF-8 where the first character takes 3 bytes to represent, while the second character takes up just 1 (all characters with ordinal < 128 have this property in UTF-8, so let's use 'a' for the example).

In this situation iconv_strpos($string, 'a') would return 1 (the second character is 'a'), while strpos($string, 'a') would return 3 (referring to the fourth character, since it cannot tell that the first three bytes are actually just one character; it assumes that the encoding is single-byte).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top