In PHP, which is faster: preg_split or explode?
Asked Answered
O

3

25

Which is faster when using it to extract keywords in a search query in php:

$keyword = preg_split('/[\s]+/', $_GET['search']);

or

$keyword = explode(' ', $_GET['search']);
Overeat answered 4/12, 2014 at 20:17 Comment(0)
M
27

Explode is faster, per PHP.net

Tip If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split().

Midwest answered 4/12, 2014 at 20:18 Comment(0)
S
13

In a simple usage explode() is than faster, see: micro-optimization.com/explode-vs-preg_split (link from web.archive.org)

But preg_split has the advantage of supporting tabs (\t) and spaces with \s.

the \s metacharacter is used to find a whitespace character.

A whitespace character can be (http://php.net/manual/en/regexp.reference.escape.php):

  • space character (32 = 0x20)
  • tab character (9 = 0x09)
  • carriage return character (13 = 0x0D)
  • new line character (10 = 0x0A)
  • form feed character (12 = 0x0C)

In this case you should see the cost and benefit.

A tip, use array_filter for "delete" empty items in array:

Example:

$keyword = explode(' ', $_GET['search']); //or preg_split
print_r($keyword);

$keyword = array_filter($arr, 'empty');
print_r($keyword);

Note: RegExp Perfomance

Sherise answered 4/12, 2014 at 20:26 Comment(6)
explode can support tabs as well. explode("\t",$string)Bumgarner
@Bumgarner I did not say that explode() does not support "tabs", I said that \s with preg_split supports "space" and "tab" at the same time. :)Sherise
No problem, but I found that sentence misleading :) best answer here anyway imhoBumgarner
in your example there is explore instead of explodePincince
"in a simple usage explode() is than faster" - is there any usage explode wouldn't be faster?Bodhisattva
@Bodhisattva I was talking about the need, how it will apply, the function itself will always be faster than anything related to regex, or even own implementations written in PHP. What I meant is that in a simple need with explodes you will get the result, if you need something complex you will need to make things more complicated, like loops from different explodes. Thanks for commenting.Sherise
B
7

General rule: if you can do something without regular expressions, do it without them!

if you want to split string by spaces, explode is way faster.

Bumgarner answered 4/12, 2014 at 20:18 Comment(2)
Tip: explode() works with other characters as wellMidwest
Yes, I know. But if he wanted for example split by spaces OR tabs OR new lines then it wouldn't be good :)Bumgarner

© 2022 - 2024 — McMap. All rights reserved.