Get the last word of a string

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

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.


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

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.

Tags:

Php

String