我有一个像这样的字符串:
红黄蓝
我想得到一个像这样的数组:
数组([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
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>
Run Code Online (Sandbox Code Playgroud)
只是爆炸它