php: Separate Spaced Words within a String

   Posted February 12, 2012 by David Kirk in PHP programming

Frequently, coders find they need to split a string into its separate words. If these words are separated by spaces, then the command options are simple.

Recently when I was hacking together some search code, I needed to breakout all the words from the search phrase. Several methods exist for doing this. Here I give a brief rundown on the strengths and speeds of each method.

If all the words are separated by a single space then one can use the php explode command. By avoiding the regular expression engine, this is the fastest method.

$words = explode(' ', $string);

The next fastest method, preg_split, uses Perl-compatible regular expression syntax and handles multiple spaces.

$words = preg_split('/\s+/', $string);

The last option is theoretically slower than the previous method. As of PHP 5.3.0 the split command has been deprecated and thus should be avoided. As it uses regular expressions syntax as well, multiple spaces are handled easily.

$words = split('\s+', $string);


About David Kirk

David Kirk is one of the original founders of tech-recipes and is currently serving as editor-in-chief. Not only has he been crafting tutorials for over ten years, but in his other life he also enjoys taking care of critically ill patients as an ICU physician.
View more articles by David Kirk

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply