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.
Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) .
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 & ...
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With