Main Content

Splitting the difference with PHP

Archive - Originally posted on "The Horse's Mouth" - 2013-04-27 21:11:07 - Graham Ellis

There are lots of ways of splitting a string into pieces - you can do it character by characters, at a specific character, and word by word. PHP provides functions for splitting strings in these ways - and more - into arrays of shorter strings.

To split a string into a list of single character strings:
  $first = str_split($record);

To split a string at a specific single character:
  $second = explode(" ",$record);

To split a string at a pattern - in this case at any number of white spaces:
  $fourth = preg_split("/\s+/",$record);

There are others too - str_getcsv will treat a string as a list of comma separated values, and split uses the deprecated "ereg" style regular expressions.

Examples in a full program at [here], and you can run the program [here].