如何获取字符串的最后一个单词


How to obtain the last word of a string

我们有这个字符串:

"I like to eat apple"

如何获得"apple"结果?

// 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];
派对

有点晚了,但这也可以

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

根据 http://www.w3schools.com/php/func_string_strrchr.asp

$str = 'I like to eat apple';
echo substr($str, strrpos($str, ' ') + 1); // apple

尝试:

$str = "I like to eat apple";
end((explode(" ",$str));

试试这个:

$array = explode(' ',$sentence);
$last = $array[count($array)-1];

获取字符串的最后一个单词

$string ="我喜欢吃苹果";
$las_word_start = strrpos($string, ' ') + 1;+1,因此我们不会在结果
中包含空格 $last_word = substr($string, $last_word_start);
echo $last_word//最后一个词:苹果

如何通过传递您需要的单词数量来获取最后一个单词或简单地从字符串中获取最后一个单词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);
<?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;
?>

输出将apple