在字符串的第一个空格处分开

Rie*_*S13 25 php split

我有一个像这样的字符串:

红黄蓝

我想得到一个像这样的数组:

数组([0] =>红色[1] =>黄色蓝色)

如何在字符串的第一个空格中拆分?我的代码不起作用

<?php
$str = "red yellow blue";
$preg = preg_split("/^\s+/", $str);
print_r($preg);
?>
Run Code Online (Sandbox Code Playgroud)

请帮我.

sil*_*ire 74

Use explode with a limit:

$array = explode(' ', $string, 2);
Run Code Online (Sandbox Code Playgroud)

Just a side note: the 3rd argument of preg_split is the same as the one for explode, so you could write your code like this as well:

$array = preg_split('#\s+#', $string, 2);
Run Code Online (Sandbox Code Playgroud)

References:

PHP: explode

PHP: preg_split

  • 对于好奇的人来说,第三个参数是数组中元素的最大数量,最后一个元素将占用剩余的一切. (2认同)

nva*_*sch 6

<?php
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>
Run Code Online (Sandbox Code Playgroud)

只是爆炸它