Main Content

PHP - dividing a string up into pieces

Archive - Originally posted on "The Horse's Mouth" - 2006-01-23 02:20:36 - Graham Ellis

"There's a function to do that ..." is the oft-used answer to many questions asked of PHP, but naturally that's followed by a plea of "what's it called". If you're looking to divide a string into a series or pieces, choose from these.

explode Returns an array, elements divided at a particular separator

strtok Returns the next element (token) each time it's called.

substr Returns a part of the incoming string based on position and length

split Returns an a array of elements divided at a case sensitive POSIX regular expression

spliti Returns an a array of elements divided at a case insensitive POSIX regular expression

preg_split Returns an array of elements divided at a Perl style regular expression

fgetcsv Reads a line from file and return it as an array. Input format is comma (or tab) separated variables, where delimiters can be included within quoted strings without causing an extra element to be generated.

unpack Unpacks the data from a binary string into an associative array

You can also use ereg, eregi and preg_match to match a string and return an array of interesting bits ... you could consider that to be yet another way to divide a string into pieces.