Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string on the last occurring space

Tags:

php

split

explode

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

like image 445
MAX POWER Avatar asked Mar 27 '12 14:03

MAX POWER


People also ask

How do you split the last element of a string?

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.

How do you split at last delimiter?

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 .

How do you split a string on the basis of space?

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.

How do you split a string into last space in Python?

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!


1 Answers

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

like image 200
Alex Turpin Avatar answered Oct 18 '22 12:10

Alex Turpin