PHP 将逗号分隔值的字符串转换为数组的最有效方法?
我已经做了一些搜索,大多数帖子都使用 phpexplode 函数来分隔字符串并将其值存储到数组中。
我需要一种有效的方法来转换:
$string = "45,34,65,57,45,23,26,72,73,56";
转换为数组,以便我可以使用 $array[3]
访问单个值。
还有比爆炸更好的方法吗?
I've done some searching around and most posts are using the php explode function to separate a string and store its values into an array.
I need an efficient way to convert:
$string = "45,34,65,57,45,23,26,72,73,56";
To an array, so I can access single values using $array[3]
.
Is there a better method than explode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Explode 是将字符串拆分为数组的最快方法,因为它是搜索分隔符的简单字符串读取器。这里不涉及正则表达式引擎开销,例如 split/preg_split/ereg 等。提高性能的唯一方法是在鼠标背上劈开头发,这就是单引号你的字符串数组,这样它就不会被解析对于变量。
但是,考虑到示例数组的大小,您可以将 pi 计算为相当于数组中每个数字的值的小数位数,并且仍然没有触及性能问题的表面。
Explode is the fastest method of splitting a string into an array, since it is a naive string reader searching for a delimiter. There is no regex engine overhead involved in this like with split/preg_split/ereg, etc. The only way you could improve performance would be splitting hairs on a mouse's back, and that would be to single quote your string array so that it's not parsed for variables.
However, given the size of your example array, you could calculate pi to the number of decimal places equivalent to the value of each number in the array and still not even scratch the surface of a performance problem.
如果您需要处理非常长的字符串,这可能是最有效的,我的意思是非常长字符串。对于您发布的示例大小的任何内容,请使用
explode
。如果您的零件长度都相同,只需执行以下操作:
This is probably the most efficient if you need to handle really long, and I mean really long, strings. For anything of the size you have posted as example, use
explode
.If your parts are all the same length, just do:
如果各部分的长度恒定,您可以检查 str_split 方法的性能。
http://www.php.net/manual/en/function.str -split.php
If the length of the parts is constant, you can check performance of the str_split method.
http://www.php.net/manual/en/function.str-split.php
您可以使用正则表达式,但这会比
explode()
慢You could use regular expression but that would be slower than
explode()
explode()
方法是最快的。preg_split()
是一种更灵活的替代方案,但速度要慢得多。The
explode()
method is quickest.preg_split()
is a more flexible alternative, but it's much slower.爆炸有什么问题吗?
您可以使用正则表达式/子字符串,但它们在开发/运行时都很慢。
最重要的是,爆炸已经为你完成了。
whats wrong with explode?
you could use regex / substring, but those are slow in both development / runtime.
best of all, explode is done for you.