-2

我已经进行了一些搜索,大多数帖子都使用 php explode 函数来分隔字符串并将其值存储到数组中。

我需要一种有效的转换方式:

$string = "45,34,65,57,45,23,26,72,73,56";

到一个数组,所以我可以使用$array[3].

有没有比爆破更好的方法?

4

6 回答 6

2

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.

于 2011-05-27T08:00:52.290 回答
2
$desiredPart = 3;

$num = strtok($string, ',');
$part = 1;

while ($part < $desiredPart && $num !== false) {
    $num = strtok(',');
    $part++;
}

echo $num;

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:

$desiredPart = 3;
$partLength = 2;
$num = substr($string, ($partLength + 1) * ($desiredPart - 1), $partLength);
于 2011-05-27T08:01:26.820 回答
1

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

于 2011-05-27T07:59:15.260 回答
1

您可以使用正则表达式,但这会比explode()

于 2011-05-27T07:57:23.123 回答
0

explode()方法是最快的。

preg_split()是一种更灵活的选择,但速度要慢得多。

于 2011-05-27T07:57:20.833 回答
-1

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.

于 2011-05-27T07:59:48.097 回答