Split a string on the last occurring space
Solution 1
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);
Solution 2
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);
Solution 3
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
Solution 4
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);
?>
Solution 5
$string="one two three four five";
list($second,$first) = explode(' ',strrev($string),2);
$first = strrev($first);
$second = strrev($second);
var_dump($first);
var_dump($second);
MAX POWER
Updated on July 09, 2022Comments
-
MAX POWER almost 2 years
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";
-
James over 8 yearsLogically, as OP is using strings and not using arrays, I'd say use the "non" array option as they don't need an array (makes the code seem more logical as it's just working with a string) but is there any performance difference?