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

时间:2012-06-14 08:35:03

标签: php

我们有那个字符串:

"I like to eat apple"

如何获得结果"apple"

8 个答案:

答案 0 :(得分: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];

答案 1 :(得分:5)

派对有点晚了,但这也有效

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

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

答案 2 :(得分:3)

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

答案 3 :(得分:3)

尝试:

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

答案 4 :(得分:2)

试试这个:

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

答案 5 :(得分:0)

如果通过传递您需要的单词量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);

答案 6 :(得分: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;

?>

输出为apple

答案 7 :(得分:0)

获取字符串的最后一句话

$ string =&#34;我喜欢吃苹果&#34 ;;
   $ las_word_start = strrpos($ string,&#39;&#39;)+ 1; // +1所以我们不在结果中包含空格    $ last_word = substr($ string,$ last_word_start);
     echo $ last_word //最后一句话:apple