php 使用 $str[0] 获取字符串的第一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1972100/
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
Getting the first character of a string with $str[0]
提问by Tatu Ulmanen
I want to get the first letter of a string and I've noticed that $str[0]works great. I am just not sure whether this is 'good practice', as that notation is generally used with arrays. This feature doesn't seem to be very well documented so I'm turning to you guys to tell me if it's all right – in all respects – to use this notation?
我想得到一个字符串的第一个字母,我注意到它$str[0]很好用。我只是不确定这是否是“好的做法”,因为该表示法通常与数组一起使用。这个功能似乎没有很好的记录,所以我转向你们告诉我是否可以 - 在所有方面 - 使用这个符号?
Or should I just stick to the good ol' substr($str, 0, 1)?
还是我应该坚持好习惯substr($str, 0, 1)?
Also, I noted that curly braces ($str{0}) works as well. What's up with that?
另外,我注意到花括号 ( $str{0}) 也可以使用。那是怎么回事?
回答by Hock
Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the []operator. Usually there's no problem at all in using $str[0](and I'm pretty sure is much faster than the substr()method).
是的。字符串可以看作是字符数组,访问数组位置的方法是使用[]运算符。通常使用完全没有问题$str[0](我很确定比substr()方法快得多)。
There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the bestoption, but it will be slightly slower.
这两种方法只有一个警告:它们将获得第一个byte,而不是第一个character。如果您使用多字节编码(例如 UTF-8),这一点很重要。如果您想支持它,请使用mb_substr(). 可以说,这些天你应该总是假设多字节输入,所以这是最好的选择,但它会稍微慢一些。
回答by Michael Morton
The {} syntax is deprecated as of PHP 5.3.0. Square brackets are recommended.
{} 语法自 PHP 5.3.0 起已弃用。建议使用方括号。
回答by gattsbr
Lets say you just want the first char from a part of $_POST, lets call it 'type'. And that $_POST['type'] is currently 'Control'. If in this case if you use $_POST['type'][0], or substr($_POST['type'], 0, 1)you will get Cback.
假设您只想要 $_POST 一部分中的第一个字符,我们称之为“类型”。而 $_POST['type'] 目前是'Control'。如果在这种情况下如果您使用$_POST['type'][0],否则substr($_POST['type'], 0, 1)您会C回来。
However, if the client side were to modify the data they send you, from typeto type[]for example, and then send 'Control' and 'Test' as the data for this array, $_POST['type'][0]will now return Controlrather than Cwhereas substr($_POST['type'], 0, 1)will simply just fail.
但是,如果客户端要修改他们发送给您的数据,例如from typeto type[],然后发送“Control”和“Test”作为该数组的数据,$_POST['type'][0]现在将返回Control而不是C而substr($_POST['type'], 0, 1)只会失败。
So yes, there may be a problem with using $str[0], but that depends on the surrounding circumstance.
所以是的,使用 可能有问题$str[0],但这取决于周围的情况。
回答by John Parker
My only doubt would be how applicable this technique would be on multi-byte strings, but if that's not a consideration, then I suspect you're covered. (If in doubt, mb_substr()seems an obviously safe choice.)
我唯一的疑问是这种技术在多字节字符串上的适用性如何,但如果这不是一个考虑因素,那么我怀疑你已经被覆盖了。(如果有疑问,这mb_substr()似乎是一个明显安全的选择。)
However, from a big picture perspective, I have to wonder how often you need to access the 'n'th character in a string for this to be a key consideration.
但是,从大局的角度来看,我不得不想知道您需要多久访问一次字符串中的第 'n 个字符才能将其作为一个关键考虑因素。
回答by Willy Stadnick
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
它会因资源而异,但您可以运行下面的脚本并亲自查看 ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
一些参考编号(在旧的 CoreDuo 机器上)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []or {}operators is more or less the same.
似乎使用[]or{}运算符或多或少是相同的。
回答by Stephen
Speaking as a mere mortal, I would stick with $str[0]. As far as I'm concerned, it's quicker to grasp the meaning of $str[0]at a glance than substr($str, 0, 1). This probably boils down to a matter of preference.
作为一个凡人,我会坚持$str[0]。就我而言,$str[0]一目了然地理解 的含义比更快substr($str, 0, 1)。这可能归结为偏好问题。
As far as performance goes, well, profile profile profile. :) Or you could peer into the PHP source code...
就性能而言,配置文件配置文件。:) 或者您可以查看 PHP 源代码...
回答by Jakir Hossain
$str = 'abcdef';
echo $str[0]; // a
回答by Sergey Burish
In case of multibyte (unicode) strings using str[0]can cause a trouble. mb_substr()is a better solution. For example:
如果使用多字节(unicode)字符串str[0]可能会导致麻烦。mb_substr()是更好的解决方案。例如:
$first_char = mb_substr($title, 0, 1);
Some details here: Get first character of UTF-8 string
这里的一些细节:获取 UTF-8 字符串的第一个字符
回答by Kaleb Brasee
I've used that notation before as well, with no ill side effects and no misunderstandings. It makes sense -- a string is just an array of characters, after all.
我以前也使用过这种表示法,没有不良副作用,也没有误解。这是有道理的——毕竟,字符串只是一个字符数组。

