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']);
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']);
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().
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):
0x20
)0x09
)0x0D
)0x0A
)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
explode()
does not support "tabs", I said that \s
with preg_split
supports "space" and "tab" at the same time. :) –
Sherise 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.
explode()
works with other characters as well –
Midwest © 2022 - 2024 — McMap. All rights reserved.
explode("\t",$string)
– Bumgarner