php: Separate Spaced Words within a String
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);
View more articles by David Kirk
Follow the reactions below and share your own thoughts.