Which is faster when using it to extract keywords in a search query in php:
$keyword = preg_split('/[\s]+/', $_GET['search']);
$keyword = explode(' ', $_GET['search']);
Here is Solutions:
We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.
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)
preg_split has the advantage of supporting tabs (
\t) and spaces with
\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 =
- tab character (9 =
- carriage return character (13 =
- new line character (10 =
- form feed character (12 =
In this case you should see the cost and benefit.
A tip, use
array_filter for “delete” empty items in array:
$keyword = explode(' ', $_GET['search']); //or preg_split print_r($keyword); $keyword = array_filter($arr, 'empty'); print_r($keyword);
Note: RegExp Perfomance
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.
Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂