Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split at the first space in a string

Tags:

php

split

I have a string like this:

red yellow blue

and I want to get an array like this :

Array ( [0] => red [1] => yellow blue )

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.

like image 898
RieqyNS13 Avatar asked Apr 25 '13 12:04

RieqyNS13


People also ask

How do you split a string at first in Python?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) .

How do you check the space at the beginning of a string?

trim() method trim space at starting and ending of a string by check unicode value '\u0020' (value of space)(most minimum value in unicode is '\u0020' = space) so it check every index from starting until get value greater than space unicode and also check from last until it get value greater than space and trim start & ...

How do you split a string with first space in Kotlin?

We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character.

What is split () function in string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

Use explode with a limit:

$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:

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

References:

PHP: explode

PHP: preg_split

like image 79
silkfire Avatar answered Sep 20 '22 00:09

silkfire