Tat*_*nen 263 php string substring
我想得到一个字符串的第一个字母,我注意到它的$str[0]效果很好.我只是不确定这是否是"良好实践",因为该符号通常用于数组.这个功能似乎没有很好的记录,所以我转向你们,告诉我是否可以 - 在所有方面 - 使用这种表示法?
或者我应该坚持好'ol' substr($str, 0, 1)?
另外,我注意到花括号($str{0})也可以.那是怎么回事?
Hoc*_*ock 373
是.字符串可以看作字符数组,访问数组位置的方法是使用[]运算符.通常在使用中没有任何问题$str[0](我很确定比substr()方法快得多).
两种方法只有一个警告:它们将获得第一个字节,而不是第一个字符.如果您使用多字节编码(例如UTF-8),这一点很重要.如果您想支持它,请使用mb_substr().可以说,这些天你应该总是假设多字节输入,所以这是最好的选择,但它会稍微慢一些.
小智 46
自PHP 5.3.0起,不推荐使用{}语法.建议使用方括号.
gat*_*sbr 22
假设您只想从$ _POST的一部分中获取第一个字符,我们称之为'type'.那个$ _POST ['type']目前是'Control'.如果在这种情况下,如果你使用$_POST['type'][0],或者substr($_POST['type'], 0, 1)你会C回来.
但是,如果客户端被修改他们给你,从数据type到type[]例如,然后发送"控制"和"测试"作为此数组中的数据,$_POST['type'][0]现在将返回Control,而不是C,而substr($_POST['type'], 0, 1)将只是简单地失败.
所以是的,使用时可能存在问题$str[0],但这取决于周围环境.
Joh*_*ker 12
我唯一怀疑的是这种技术对多字节字符串的适用性如何,但如果这不是一个考虑因素,那么我怀疑你被覆盖了.(如果有疑问,mb_substr()似乎是一个明显安全的选择.)
但是,从大局的角度来看,我想知道你需要多久访问"第n个字符的字符串,这是一个重要的考虑因素.
它会因资源而异,但你可以运行下面的脚本并亲自看看;)
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
一些参考号码(在旧的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
Run Code Online (Sandbox Code Playgroud)
似乎使用[]或{}运算符或多或少相同.
作为一个凡人,我会坚持$str[0].就我而言,$str[0]一眼就能更快地掌握其含义substr($str, 0, 1).这可能归结为偏好问题.
就性能而言,简介配置文件配置文件.:)或者您可以查看PHP源代码......
小智 6
如果使用多字节(unicode)字符串str[0]可能会导致麻烦。mb_substr()是更好的解决方案。例如:
$first_char = mb_substr($title, 0, 1);
Run Code Online (Sandbox Code Playgroud)
这里的一些细节:获取 UTF-8 字符串的第一个字符
$str = 'abcdef';
echo $str[0]; // a
Run Code Online (Sandbox Code Playgroud)