35

I have tried a few things to get a last part out I done this:

$string = 'Sim-only 500 | Internet 2500';
preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$string
AND
preg_match("/[^ ]*$/","",{abo_type[1]})

The first one won't work and the second returns an array but a realy need string.

Mohammed Zayan
  • 859
  • 11
  • 20
Roy van Wensen
  • 580
  • 1
  • 5
  • 13
  • Can you please specify what you actually want? Just the last word of any string? In this case the 2500? – ranieuwe Sep 04 '13 at 11:45
  • Yes i want the 2500, and yes i want i any case the last word. – Roy van Wensen Sep 04 '13 at 11:46
  • 2
    possible duplicate of [How to get last string in sentences using php?](http://stackoverflow.com/questions/11029447/how-to-get-last-string-in-sentences-using-php) – Benoît Sep 04 '13 at 11:47
  • You might find [`array_pop(s($str)->words())`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L363) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). – caw Jul 27 '16 at 03:48

10 Answers10

74

If you're after the last word in a sentence, why not just do something like this?

$string = '​Sim-only 500 ​| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);

echo $last_word;

I wouldn't recommend using regular expressions as it's unnecessary, unless you really want to for some reason.

$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.

Using a substr() method would be better than both of these if resources/efficiency/overhead is a concern.

$string = 'Retrieving the last word of a string using PHP.';
$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start); // $last_word = PHP.

it is faster, although it really doesn't make that much of a difference on things like this. If you're constantly needing to know the last word on a 100,000 word string, you should probably be going about it in a different way.

SubjectCurio
  • 4,702
  • 3
  • 32
  • 46
  • 1
    So, you will created a 1000 length array from a 1000-word sentence just to get the last word? – Sebastian Aug 13 '14 at 00:57
  • 2
    @Sebastian Context matters, but in case of 1,000 words, yes I probably still would. Unless you're running the script thousands/millions of times, the amount of time you'd save doing it another way in comparison to this way wouldn't be more than the amount of time I took to write this comment. – SubjectCurio Aug 13 '14 at 17:56
  • Your last example misses the first letter when there is only one word in the string. Fixed code is: $last_word = substr($string, strrpos(' ' . $string, ' ')); – Chris Jenks May 10 '22 at 23:24
9

This should work for you:

$str = "fetch the last word from me";
$last_word_start = strrpos ( $str , " ") + 1;
$last_word_end = strlen($str) - 1;
$last_word = substr($str, $last_word_start, $last_word_end);
hunter
  • 91
  • 2
  • 5
    You do not need `$last_word_end` here. When the third parameter of `substr` is omitted, the function takes everything from `$last_word_start` to the end of the string. If you insist on having it, then it should be `$last_word_end = strlen($str) - $last_word_start` (yours usually won't give a wrong result, but it is meaningless; it WILL be wrong if the string contains no whitespaces). – Vedran Šego Apr 26 '14 at 14:18
6

It depends on what you try to do (it is hard to understand from your description) but to get the last word from a string you can do:

$split = explode(" ", $string);

echo $split[count($split)-1];

See How to obtain the last word of a string for more information.

Community
  • 1
  • 1
ranieuwe
  • 2,268
  • 1
  • 24
  • 30
3

The existing solutions all work fine, but I wanted a one-liner. explode() will split a sentence into words, but trying to pass it directly into array_pop() or end() gives a "Only variables should be passed by reference" notice. array_slice() to the rescue:

$string = 'Sim-only 500 | Internet 2500';
echo array_slice(explode(' ', $string), -1)[0];
Indrek
  • 867
  • 8
  • 27
1

There you go a generic function to get last words from string

public function get_last_words($amount, $string)
{
    $amount+=1;
    $string_array = explode(' ', $string);
    $totalwords= str_word_count($string, 1, 'àáãç3');
    if($totalwords > $amount){
        $words= implode(' ',array_slice($string_array, count($string_array) - $amount));
    }else{
        $words= implode(' ',array_slice($string_array, count($string_array) - $totalwords));
    }

    return $words;
}
$string = '​Sim-​only 500 | Internet 2500​';
echo get_last_words(1,  $string );
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
1

If you want to wrap the last word with a span:

<?php
/**
 * Wrap last word with span
 * @author: Elron
 * https://stackoverflow.com/questions/18612872/get-the-last-word-of-a-string
 */
function wrap_last_word($string) {
    // Breaks string to pieces
    $pieces = explode(" ", $string);

    // Modifies the last word
    $pieces[count($pieces)-1] = '<span class="is-last-word">' . $pieces[count($pieces)-1] . '</span>';

    // Returns the glued pieces
    return implode(" ", $pieces);
}

wrap_last_word('hello this is wrapped');
// returns this:
// hello this is <span class="is-last-word">wrapped</span>
Elron
  • 1,235
  • 1
  • 13
  • 26
0

Here is another way to get the last word from a string

$my_string = "fetch the last word from me";
 
// Explode the string into an array
$my_string = explode(" ", $my_string);

// target the last word with end() function 
$my_string = end($my_string);

echo $my_string;

Result me

Sleek Geek
  • 4,638
  • 3
  • 27
  • 42
0

One-line solution using regexp:

preg_replace('/.*\s/', '', $string);

This suppress everything ending by a space, and since regexp are always matched "as long as possible", this will match everything but the last word. This has also the advantage on working with any "space" character (tab, newline...).

But the best performance/ressources consumption solution is (does not work if only one word):

substr($string, strrpos($string, ' ') + 1);
0

There is a one-line solution.

basename(str_replace(' ', '/', 'hello world'));

will return world

X 47 48 - IR
  • 1,250
  • 1
  • 15
  • 28
-1

Just use this function

function last_word($string)
{
    $pieces = explode(' ', $string);
    return array_pop($pieces);
}
Appoodeh
  • 104
  • 1
  • 8