3

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?

5
  • 1
    You can use explode function to split string into array Commented Mar 19, 2013 at 11:49
  • Im afraid there won't be a faster alternate to using a regular expression, because of that condition that before colon there should not be an *. Otherwise you could try explode and compare the results Commented Mar 19, 2013 at 11:50
  • only other way I can think of is to loop over the string yourself and manually build the array, but it's probably slower than using preg. Commented Mar 19, 2013 at 11:51
  • @bhumi: in general, yes, but explode doesn't support regexes, and does a blind split. OP wants *: excluded from split points. Commented Mar 19, 2013 at 11:52
  • @MarcB - I can confirm than string looping is like 10 times slower. Commented Mar 19, 2013 at 12:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I haven't tested thoroughly but getting the *: back seems to be very slow, even with array_map().
Perhaps its not needed, unless its for display purposes. I have had an idea, watch the edit on my post shortly.
Now theres no need to put the *: back in. We leave them in place prior to the split.
Now your code is faster because it no longer follows the spec.
How are you testing the timing of the script?
|
0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.