php 在字符串的第一个空格处拆分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16214593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
split at the first space in a string
提问by RieqyNS13
I have a string like this:
我有一个这样的字符串:
red yellow blue
红黄蓝
and I want to get an array like this :
我想得到一个这样的数组:
Array ( [0] => red [1] => yellow blue )
数组( [0] => 红色 [1] => 黄色蓝色)
how to split at the first space in a string ? my code doesn't work
如何在字符串的第一个空格处拆分?我的代码不起作用
<?php
$str = "red yellow blue";
$preg = preg_split("/^\s+/", $str);
print_r($preg);
?>
please help me.
请帮我。
回答by silkfire
Use explode
with a limit:
explode
有限制地使用:
$array = explode(' ', $string, 2);
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:
只是一个旁注: 的第三个参数与preg_split
for 的相同explode
,因此您也可以这样编写代码:
$array = preg_split('#\s+#', $string, 2);
References:
参考:
回答by nvanesch
<?php
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>
just explode it
爆炸吧
回答by chandresh_cool
回答by user2597484
You can use explode, but if you aren't 100% sure you'll have the same # of spaces (explosions) every time, you can use ltrimto remove the first word and space
您可以使用expand,但如果您不是 100% 确定每次都会有相同的空格数(爆炸),您可以使用ltrim删除第一个单词和空格
<?php
$full='John Doe Jr.';
$full1=explode(' ', $full);
$first=$full1[0];
$rest=ltrim($full, $first.' ');
echo "$first + $rest";
?>
回答by Yussuf Maqsood
You can use explodethis way:
您可以这样使用爆炸:
$stringText = "red yellow blue";
$colours = explode(" ", $stringText);
echo $colours[0]; //red
echo $colours[1]; //yellow
echo $colours[2]; //blue
You can also get all the elements of $colours by foreach Loop, but in this case explode is better
也可以通过 foreach 循环获取 $colours 的所有元素,但这种情况下 expand 更好