【发布时间】:2010-12-20 01:27:33
【问题描述】:
如何将字符串分解为一个或多个空格或制表符?
例子:
A B C D
我想把它变成一个数组。
【问题讨论】:
-
零个或多个空格意味着每个元素最多有一个字符,或者您将有无限多个空元素。你确定这是你想要的吗?
-
是的,应该是“一个或多个空格”。
如何将字符串分解为一个或多个空格或制表符?
例子:
A B C D
我想把它变成一个数组。
【问题讨论】:
为了占全宽空间比如
full width
您可以将 Bens 的答案扩展到此:
$searchValues = preg_split("@[\s+ ]@u", $searchString);
来源:
(我没有足够的声誉来发表评论,所以我写了这个作为答案。)
【讨论】:
假设$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
【讨论】:
这行得通:
$string = 'A B C D';
$arr = preg_split('/\s+/', $string);
【讨论】:
\s 没有任何好处。
以制表符分隔:
$comp = preg_split("/\t+/", $var);
用空格/制表符/换行符分隔:
$comp = preg_split('/\s+/', $var);
仅用空格分隔:
$comp = preg_split('/ +/', $var);
【讨论】:
preg_split('/\s{2,}/', $var);,
\t 没有任何好处。
作者要求explode,你可以这样用explode
$resultArray = explode("\t", $inputString);
注意:你必须使用双引号,而不是单引号。
【讨论】:
我想你想要preg_split:
$input = "A B C D";
$words = preg_split('/\s+/', $input);
var_dump($words);
【讨论】:
不要使用explode,而是尝试preg_split:http://www.php.net/manual/en/function.preg-split.php
【讨论】:
$parts = preg_split('/\s+/', $str);
【讨论】:
$parts = preg_split('/\s+/', $str, -1, PREG_SPLIT_NO_EMPTY);,而不是删除可能为空的最后一部分