用空格分割字符串

gra*_*nja 1 php regex

如何通过白色空间分割字符串无论白色空间有多长?

例如,从以下字符串:

"the    quick brown   fox        jumps   over  the lazy   dog"
Run Code Online (Sandbox Code Playgroud)

我会得到一个数组

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog'];
Run Code Online (Sandbox Code Playgroud)

Qui*_*ick 6

您可以使用正则表达式轻松完成此操作:

$string = 'the quick     brown fox      jumps 



over the 

lazy dog';


$words = preg_split('/\s+/', $string, -1, PREG_SPLIT_NO_EMPTY);

print_r($words);
Run Code Online (Sandbox Code Playgroud)

这会产生以下输出:

Array
(
    [0] => the
    [1] => quick
    [2] => brown
    [3] => fox
    [4] => jumps
    [5] => over
    [6] => the
    [7] => lazy
    [8] => dog
)
Run Code Online (Sandbox Code Playgroud)

  • “-1”表示没有限制。如果您在那里指定一个正数,那么它只会进行那么多匹配。就像如果我将其设置为 3,它将返回 `[0] => the, [1] => Quick, [2] => Brown Fox Jumps...`。`PREG_SPLIT_NO_EMPTY` 意味着它不会返回空字符串。例如,如果您使用“\s”而不是“\s+”,那么它会将所有空格分解为单独的实体,并仅返回一堆空字符串以及您想要的文本。`PREG_SPLIT_NO_EMPTY` 只是告诉它忽略空项目并只给我们我们想要的东西。 (2认同)