3

we have that string:

"I like to eat apple"

How can I obtain the result "apple" ?

Oscar
  • 1,093
  • 4
  • 21
  • 31

8 Answers8

20
// Your string
$str = "I like to eat apple";
// Split it into pieces, with the delimiter being a space. This creates an array.
$split = explode(" ", $str);
// Get the last value in the array.
// count($split) returns the total amount of values.
// Use -1 to get the index.
echo $split[count($split)-1];
Rick Kuipers
  • 6,616
  • 2
  • 17
  • 37
9

a bit late to the party but this works too

$last = strrchr($string,' ');

as per http://www.w3schools.com/php/func_string_strrchr.asp

user2029890
  • 2,493
  • 6
  • 34
  • 65
4
$str = 'I like to eat apple';
echo substr($str, strrpos($str, ' ') + 1); // apple
flowfree
  • 16,356
  • 12
  • 52
  • 76
3

Try:

$str = "I like to eat apple";
end((explode(" ",$str));
kenorb
  • 155,785
  • 88
  • 678
  • 743
m4rtijn
  • 55
  • 1
2

Try this:

$array = explode(' ',$sentence);
$last = $array[count($array)-1];
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
Milan Halada
  • 1,943
  • 18
  • 28
1

Get last word of string

$string ="I like to eat apple";
$las_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start);
echo $last_word // last word : apple

Reena Mori
  • 647
  • 6
  • 15
0

How about this get last words or simple get last word from string just by passing the amount of words you need get_last_words(1, $str);

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;
}
$str = 'I like to eat apple';
echo get_last_words(1,  $str);
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
0
<?php
// your string
$str = 'I like to eat apple';

// used end in explode, for getting last word
$str_explode=end(explode("|",$str));
echo    $str_explode;

?>

Output will be apple.

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
Talha Mughal
  • 51
  • 1
  • 2