Sosumi
Sosumi

Reputation: 779

Fastest method of splitting string into an array in PHP

I have a PHP script which splits strings into arrays using prey_split. The preg_split code is:

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

Which essentially splits the string where there is a colon, without a preceding asterisk. For example: "h*:el:lo" turns into array("h*:el", "lo")

This process is quite resource intensive and slow when splitting large amounts of strings. Is there a faster method to achieve this?

Upvotes: 3

Views: 335

Answers (2)

Alan Moore
Alan Moore

Reputation: 75232

Are you required to use preg_split()? Because it's easier to use preg_match_all():

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

Upvotes: 0

Husman
Husman

Reputation: 6909

You could try something like this:

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

I'm not sure of what the speed will be like., but once you remove the *: bits form the string, its simple to explode. Perhaps you can put the *: back in after the operation if you need it.

Upvotes: 1

Related Questions