GSTAR GSTAR - 2 months ago 11x
PHP Question

Split a string into two parts

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 one.
The second part needs to contain just the last word.

Can anyone advise?

EDIT: The two parts need to be returned as strings, not arrays, e.g:

$part1 = "one two three four";

$part2 = "five";


Couple ways you can go about it.

Array operations:

$string ="one two three four five";
$words = explode(' ', $string);
$last_word = array_pop($words);
$first_chunk = implode(' ', $words);

String operations:

$string="one two three four five";
$last_space = strrpos($string, ' ');
$last_word = substr($string, $last_space);
$first_chunk = substr($string, 0, $last_space);