155

如何将字符串分解为一个或多个空格或制表符?

例子:

A      B      C      D

我想把它变成一个数组。

4

8 回答 8

358
$parts = preg_split('/\s+/', $str);
于 2009-11-24T21:17:21.610 回答
58

按制表符分隔:

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

用空格/制表符/换行符分隔:

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

仅用空格分隔:

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

于 2014-11-27T20:53:38.447 回答
24

这有效:

$string = 'A   B C          D';
$arr = preg_split('/\s+/', $string);
于 2009-11-24T21:17:59.847 回答
19

作者要求爆炸,你可以这样使用爆炸

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

注意:您必须使用双引号,而不是单引号。

于 2016-07-20T12:28:16.970 回答
10

我想你想要preg_split

$input = "A  B C   D";
$words = preg_split('/\s+/', $input);
var_dump($words);
于 2009-11-24T21:19:04.633 回答
4

而不是使用爆炸,尝试preg_split:http ://www.php.net/manual/en/function.preg-split.php

于 2009-11-24T21:17:42.280 回答
3

为了考虑全宽空间,例如

full width

您可以将 Bens 的答案扩展到此:

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

资料来源:

(我没有足够的声誉发表评论,所以我写了这个作为答案。)

于 2016-03-02T01:40:44.530 回答
1

假设$string = "\tA\t B \tC \t D ";(混合制表符和空格,包括前导制表符和尾随空格)

显然,仅拆分空格或仅制表符是行不通的。不要使用这些

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

使用这些

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

可以在此处找到以下所有技术的演示。

参考水平空白

于 2021-07-14T13:57:41.273 回答