162

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • zero or more spaces implies that either each element will have at most one character, or that you'll have infinitely many empty elements. Are you sure this is what you want? – bdonlan Nov 24 '09 at 21:14
  • Yeah, that should probably be "one or more spaces". – Michael Myers Nov 24 '09 at 21:15

9 Answers9

375
$parts = preg_split('/\s+/', $str);
Ben James
  • 121,135
  • 26
  • 193
  • 155
  • 11
    Instead of removing the last part which may be empty, one can use: ```$parts = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);``` – coeing Dec 19 '18 at 08:53
63

To separate by tabs:

$comp = preg_split("/\t+/", $var);

To separate by spaces/tabs/newlines:

$comp = preg_split('/\s+/', $var);

To seperate by spaces alone:

$comp = preg_split('/ +/', $var);

Dharman
  • 30,962
  • 25
  • 85
  • 135
AliAvci
  • 1,127
  • 10
  • 20
25

This works:

$string = 'A   B C          D';
$arr = preg_split('/\s+/', $string);
Dharman
  • 30,962
  • 25
  • 85
  • 135
schneck
  • 10,556
  • 11
  • 49
  • 74
  • There is no benefit to writing `\s` inside of a character class. – mickmackusa Jul 14 '21 at 13:26
  • @mickmackusa Could you clarify? This is pretty similar to the first example in the [docs](https://www.php.net/manual/en/function.preg-split.php). – Hashim Aziz Aug 29 '23 at 21:56
  • 1
    @Hash the documentation's example is splitting on whitespaces AND commas. When you have multiple items to list (`[\s,]`), then creating a "character class" is appropriate. When you are only splitting on `\s` (whitespaces), then use the current syntax in this answer (edited by Dharman after I commented). – mickmackusa Aug 29 '23 at 23:19
19

The author asked for explode, to you can use explode like this

$resultArray = explode("\t", $inputString);

Note: you must used double quote, not single.

lucsan
  • 712
  • 9
  • 10
10

I think you want preg_split:

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);
jheddings
  • 26,717
  • 8
  • 52
  • 65
4

instead of using explode, try preg_split: http://www.php.net/manual/en/function.preg-split.php

Brian Schroth
  • 2,447
  • 1
  • 15
  • 26
3

In order to account for full width space such as

full width

you can extend Bens answer to this:

$searchValues = preg_split("@[\s+ ]@u", $searchString);

Sources:

(I don't have enough reputation to post a comment, so I'm wrote this as an answer.)

MPS
  • 345
  • 2
  • 12
  • This answer should not be used. The character class contains: 1. Whitespaces 2. Plus symbols and 3. literal spaces. There is a fundamental lack of understanding in this answer. – mickmackusa Aug 29 '23 at 23:23
1

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, deny 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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • 1
    This is the first answer that shows the concept of horizontal whitespaces. This is the most correct answer now, as the question asked only about tabs and spaces. – Dharman Jul 14 '21 at 14:05
-2

For anyone who needs to quickly grab just one word from the string:

$name = "John Doe";
preg_split('/\s+/', $name)[0];
// John

Note the [0] which will only grab the first word - modify as necessary for whichever element in the array you need.

Or for an even more performant but less robust solution to do the same thing:

$name = "John Doe";
strtok($string, " ")[0];
// John
Hashim Aziz
  • 4,074
  • 5
  • 38
  • 68
  • This answer contains redundant insights, has typos, and is giving misleading information. `strtok()` does not understand regex. https://3v4l.org/g7ehT It looks like you are posting on the wrong page. [How to get the first word of a sentence in PHP?](https://stackoverflow.com/q/2476789/2943403) – mickmackusa Aug 29 '23 at 23:25
  • @mickmackusa The XY problem can cause people to search for too specific a solution (`explode`) even when they just need the first word from the string. That's how I ended up on this question and no doubt countless more are from Google, so I thought it best to answer that question with an appropriate solution. – Hashim Aziz Aug 29 '23 at 23:35
  • If your job was to organise Stack Overflow content, would you welcome contributions which stretch the requirements of every page (bear in mind, there are MILLIONS of pages to manage). No. By having narrow question scope, Stack Overflow is in a better position to collect unique insights on a given topic. – mickmackusa Aug 29 '23 at 23:44