Split a string into two parts

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);

What you need is to split the input string on the last space. Now a last space is a space which is not followed by any more spaces. So you can use negative lookahead assertion to find the last space:

$string="one two three four five";
$pieces = preg_split('/ (?!.* )/',$string);

Have a look at the explode function in PHP

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter

Tags:

Php