In PHP, which is faster: preg_split or explode?

一曲冷凌霜 提交于 2019-11-26 23:19:25

问题


This may sound like a stupid question, but: 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']);

回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/27303235/in-php-which-is-faster-preg-split-or-explode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!