I need to split a string into two parts. The string contains words separated by a space and can contain any number of words, e.g:
$string = "one two three four five";
The first part needs to contain all of the words except for the last word.
The second part needs to contain just the last word.
EDIT: The two parts need to be returned as strings, not arrays, e.g:
$part1 = "one two three four";
$part2 = "five";
To split a string and get the last element of the array, call the split() method on the string, passing it the separator as a parameter, and then call the pop() method on the array, e.g. str. split(','). pop() . The pop() method will return the last element from the split string array.
Use the str. rsplit() method with maxsplit set to 1 to split a string on the last occurrence of a delimiter, e.g. my_str. rsplit(',', 1) . The rsplit() method splits from the right, and only performs a single split when maxsplit is set to 1 .
To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.
Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 . Copied!
Use strrpos
to get last space character's position, then substr
to divide the string with that position.
<?php
$string = 'one two three four five';
$pos = strrpos($string, ' ');
$first = substr($string, 0, $pos);
$second = substr($string, $pos + 1);
var_dump($first, $second);
?>
Live example
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