3

we have that string:

"I like to eat apple"

How can I obtain the result "apple" ?

Oscar
  • 1,083
  • 4
  • 21
  • 29

8 Answers8

18
// 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,498
  • 2
  • 16
  • 36
8

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,283
  • 6
  • 30
  • 61
4
$str = 'I like to eat apple';
echo substr($str, strrpos($str, ' ') + 1); // apple
flowfree
  • 16,008
  • 12
  • 48
  • 75
3

Try:

$str = "I like to eat apple";
end((explode(" ",$str));
kenorb
  • 137,499
  • 74
  • 643
  • 694
m4rtijn
  • 55
  • 1
2

Try this:

$array = explode(' ',$sentence);
$last = $array[count($array)-1];
Will Vousden
  • 31,330
  • 9
  • 80
  • 92
Milan Halada
  • 1,863
  • 18
  • 25
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
  • 62,293
  • 9
  • 87
  • 115
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
  • 12,791
  • 16
  • 74
  • 91
Talha Mughal
  • 51
  • 1
  • 1