web-dev-qa-db-ja.com

文字列の最初のスペースで分割

私はこのような文字列を持っています:

赤黄青

そして、私はこのような配列を取得したい:

配列([0] =>赤[1] =>黄青)

文字列の最初のスペースで分割する方法は?私のコードは機能しません

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

私を助けてください。

25
RieqyNS13

explodeを制限付きで使用します。

$array = explode(' ', $string, 2);

ちょっとした注意:preg_splitの3番目の引数はexplodeの引数と同じなので、次のようにコードを書くこともできます。

$array = preg_split('#\s+#', $string, 2);

参照:

PHP:分解

PHP:preg_split

73
silkfire
<?php
$string = "red yellow blue";
$result = explode(" ", $string, 2);
print_r($result);
?>

ただ爆発させる

6
nvanesch

このような爆発関数を使用できます

print_r(explode(' ', $str, 2));

制限が設定されます。詳細を確認してください こちら

3
chandresh_cool

explode を使用できますが、毎回同じ数のスペース(爆発)があることを100%確信できない場合は、 ltrim を使用して削除できます最初の単語とスペース

<?php
$full='John Doe Jr.';
$full1=explode(' ', $full);
$first=$full1[0];
$rest=ltrim($full, $first.' ');
echo "$first + $rest";
?>
2
user2597484