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']);
vvvvv
  • 25,404
  • 19
  • 49
  • 81
Marco
  • 2,687
  • 7
  • 45
  • 61

3 Answers3

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().

Machavity
  • 30,841
  • 27
  • 92
  • 100
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

Protomen
  • 9,471
  • 9
  • 57
  • 124
  • explode can support tabs as well. `explode("\t",$string)` – Forien Dec 04 '14 at 20:55
  • @Forien 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. :) – Protomen Dec 04 '14 at 20:57
  • 2
    No problem, but I found that sentence misleading :) best answer here anyway imho – Forien Dec 04 '14 at 20:58
  • 1
    in your example there is explore instead of explode – magento4u_com Mar 13 '19 at 08:19
  • "in a simple usage explode() is than faster" - is there *any* usage explode wouldn't be faster? – eis Apr 13 '21 at 16:24
  • @eis 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. – Protomen Apr 13 '21 at 16:35
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.

Forien
  • 2,712
  • 2
  • 13
  • 30