PHP:字符串索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/885241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: string indexing
提问by codymanix
What is the difference between $str[n] and $str{n}, given that $str is a string.
$str[n] 和 $str{n} 之间有什么区别,因为 $str 是一个字符串。
I noticed that both seem to work the same, except that {} does not occur in any documentation I found.
我注意到两者的工作方式似乎相同,只是在我找到的任何文档中都没有出现 {}。
回答by Paolo Bergantino
They are the same. However, they are getting rid of the {}syntax, so you should go with [].
他们是一样的。但是,他们正在摆脱{}语法,因此您应该使用[].
根据手册:
Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in
$str[42]. Think of a string as an array of characters for this purpose. The functionssubstr()andsubstr_replace()can be used when you want to extract or replace more than 1 character.Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted
E_NOTICEfor reading (yielding an empty string) andE_WARNINGfor writing (leaving the string untouched).Note: Strings may also be accessed using braces, as in
$str{42}, for the same purpose.
可以通过使用方数组括号指定字符串后所需字符的从零开始的偏移量来访问和修改字符串中的字符,如
$str[42]. 为此,可以将字符串视为字符数组。当您要提取或替换 1 个以上的字符时substr(),substr_replace()可以使用和函数。注意:从 PHP 7.1.0 开始,还支持负字符串偏移量。这些指定从字符串末尾的偏移量。以前,
E_NOTICE为读取(产生空字符串)和E_WARNING写入(保持字符串不变)发出负偏移量。注意:
$str{42}出于同样的目的,也可以使用大括号来访问字符串,例如。
回答by Patrik
Be careful, $str[n]and $str{n}give n-th Byte of String, not n-th character of String. For multibyte encoding (UTF-8, etc.) one character doesn't need to be one Byte.
小心,$str[n]并$str{n}给出 的第 n 个字节String,而不是 的第 n 个字符String。对于多字节编码(UTF-8 等),一个字符不必是一个字节。
$str{0}– first Byte of string
$str{0}– 字符串的第一个字节
mb_substr($str, 0, 1)– first character of string (including multibyte charsets)
mb_substr($str, 0, 1)– 字符串的第一个字符(包括多字节字符集)

