Split a string on the last occurring space [duplicate]
Asked Answered
T

11

12

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

Tape answered 27/3, 2012 at 14:41 Comment(2)
strrpos would be a good starting point. The manual has more.Lieabed
This is not the response for the exact question but related to the title because I was looking for that almost equal two parts and I achived that with using wordwrap.Rosauraroscius
D
27

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);
Docilla answered 27/3, 2012 at 14:47 Comment(1)
Logically, 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?Supertanker
H
9

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);
Hugely answered 27/3, 2012 at 14:45 Comment(0)
T
5

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

Theodosia answered 27/3, 2012 at 14:46 Comment(0)
M
3
$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);
Mound answered 27/3, 2012 at 14:47 Comment(0)
D
3

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

Deface answered 27/3, 2012 at 14:48 Comment(0)
K
1
$string = "one two three four five";
$array = explode(" ", $string); // Split string into an array

$lastWord = array_pop($array); // Get the last word
// $array now contains the first four words
Kooima answered 27/3, 2012 at 14:46 Comment(0)
H
1

This should do it:

$arr = explode(' ', $string);
$second = array_pop($arr);
$result[] = implode(' ', $arr);
$result[] = $second;
Hendecasyllable answered 27/3, 2012 at 14:48 Comment(0)
C
1

Something like this would do it, although it's not particularly elegant.

$string=explode(" ", $string);
$new_string_1=$string[0]." ".$string[1]." ".$string[2]." ".$string[3];
$new_string_2=$string[4];
Colligate answered 27/3, 2012 at 14:49 Comment(0)
C
1
$string="one two three four five";
$matches = array();
preg_match('/(.*?)(\w+)$/', $string, $matches);
print_r($matches);

Output:

Array ( [0] => one two three four five [1] => one two three four [2] => five )

Then your parts would be $matches[1] and $matches[2]

Chromaticness answered 27/3, 2012 at 14:51 Comment(0)
K
1

my solution in Perl :)... PHP and Perl are similar :) $string="one five three four five";

@s = split(/\s+/, $string) ;

$s1 = $string ;
$s1 =~ s/$s[-1]$//e ;

$s2 = $s[-1] ;
print "The first part: $s1 \n";
print "The second part: $s2 \n";
Kelwunn answered 27/3, 2012 at 14:56 Comment(0)
R
0

Greedily traverse the characters in the input string then match the latest occurring space and split on that. Super easy, no lookaround or captures or any other reasons to slow down the regex engine.

\K means "forget all matched characters up to this point".

Code: (Demo)

$string = "one two three four five";
var_export(
    preg_split('/.*\K /', $string)
);

Output:

array (
  0 => 'one two three four',
  1 => 'five',
)

Or as individual variables: (Demo)

[$part1, $part2] = preg_split('/.*\K /', $string);
var_export($part1);
echo "\n";
var_export($part2);
Ruffianism answered 30/7, 2021 at 14:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.