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.
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.
$parts = preg_split('/\s+/', $str);
$parts = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);
–
Willard 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);
preg_split('/\s{2,}/', $var);
which requires atleast two spaces, –
Cerelly \t
inside of a character class. –
Ephesus This works:
$string = 'A B C D';
$arr = preg_split('/\s+/', $string);
\s
inside of a character class. –
Ephesus [\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). –
Ephesus The author asked for explode, to you can use explode like this
$resultArray = explode("\t", $inputString);
Note: you must used double quote, not single.
I think you want preg_split
:
$input = "A B C D";
$words = preg_split('/\s+/', $input);
var_dump($words);
instead of using explode, try preg_split: http://www.php.net/manual/en/function.preg-split.php
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.)
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
© 2022 - 2025 — McMap. All rights reserved.