PHP中最快的将字符串分割成数组的方法


Fastest method of splitting string into an array in PHP

我有一个PHP脚本,使用prey_split将字符串拆分为数组。preg_split代码为:

preg_split("~(?<!'*):~", $val);

它实际上拆分了前面没有星号的冒号字符串。例如:"h*:el:lo"变为array("h*:el", "lo")

当分割大量的字符串时,这个过程是相当资源密集和缓慢的。是否有更快的方法来实现这一点?

你可以尝试这样做:

$string = "h*:el:lo";
$string = str_replace("*:", "#", $string);
$array = explode(":", $string);

我不确定速度会是什么样子。,但是一旦你从字符串中去掉*:位,它很容易爆炸。

如果需要的话,可以在操作后把*:放回去。

是否需要使用preg_split() ?因为更容易使用preg_match_all():

preg_match_all('/(?:^|:)([^*:]+(?:'*.[^*:]+)*)/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[1];