为什么使用 iconv_strpos 而不是 strpos?
与 strpos() 相比, iconv_strpos() 的返回值是出现在针之前的字符数,而不是到找到针的位置的字节偏移量。 (来源:http://www.php.net/manual/en/ function.iconv-strpos.php)
以下代码示例显示 iconv_strpos()
和 strpos()
返回相同的值。
$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
为什么我应该使用 iconv_strpos 而不是 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它通常仅在使用多字节编码(例如 UTF-8 或 UTF-16)时才相关。
一个字符可能由多个字节组成(UTF-8 中的非 7 位 ASCII 字符就是这种情况 - 这些字符的编码长度是可变的。UTF-16 有 2 字节字符)。
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).
当您使用多字节编码时,单个字符可以由可变数量的字节表示(例如,在 UTF-8 中为 1 到 4)。这与单字节编码相反,单字节编码中每个字节始终代表一个字符。
考虑以 UTF-8 编码的双字符字符串,其中第一个字符需要 3 个字节来表示,而第二个字符仅占用 1 个字节(序数 < 128 的所有字符在 UTF-8 中都具有此属性,因此让我们使用
'a'
为例)。在这种情况下,
iconv_strpos($string, 'a')
将返回 1(第二个字符是'a'
),而strpos($string, 'a ')
将返回 3(指的是第四个字符,因为它无法判断前三个字节实际上只是一个字符;它假设编码是单字节)。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'
), whilestrpos($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).