Explode string by one or more spaces or tabs

Viewed 177447

How can I explode a string by one or more spaces or tabs?

Example:

A      B      C      D

I want to make this an array.

8 Answers

Assuming $string = "\tA\t B \tC \t D "; (a mix of tabs and spaces including leading tab and trailing space)

Obviously splitting on just spaces or just tabs will not work. Don't use these:

preg_split('~ +~', $string) // one or more literal spaces, allow empty elements
preg_split('~ +~', $string, -1, PREG_SPLIT_NO_EMPTY) // one or more literal spaces, deny empty elements

preg_split('~\t+~', $string) // one or more tabs, allow empty elements
preg_split('~\t+~', $string, -1, PREG_SPLIT_NO_EMPTY) // one or more tabs, deny empty elements

Use these:

preg_split('~\s+~', $string) // one or more whitespace character, allow empty elements
preg_split('~\s+~', $string, -1, PREG_SPLIT_NO_EMPTY), // one or more whitespace character, deny empty elements

preg_split('~[\t ]+~', $string) // one or more tabs or spaces, allow empty elements
preg_split('~[\t ]+~', $string, -1, PREG_SPLIT_NO_EMPTY)  // one or more tabs or spaces, allow empty elements

preg_split('~\h+~', $string) // one or more horizontal whitespaces, allow empty elements
preg_split('~\h+~', $string, -1, PREG_SPLIT_NO_EMPTY) // one or more horizontal whitespaces, deny empty elements

A demonstration of all techniques below can be found here.

Reference Horizontal Whitespace

Related