3

我们有那个字符串:

"I like to eat apple"

我怎样才能得到结果"apple"

4

8 回答 8

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];
于 2012-06-14T08:36:11.763 回答
8

聚会有点晚了,但这也有效

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

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

于 2014-03-05T17:52:46.730 回答
3
$str = 'I like to eat apple';
echo substr($str, strrpos($str, ' ') + 1); // apple
于 2012-06-14T08:37:05.570 回答
3

尝试:

$str = "I like to eat apple";
end((explode(" ",$str));
于 2014-01-09T20:48:40.163 回答
2

试试这个:

$array = explode(' ',$sentence);
$last = $array[count($array)-1];
于 2012-06-14T08:37:55.100 回答
1

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

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

于 2017-05-31T06:23:39.250 回答
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);
于 2013-12-25T12:33:19.507 回答
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.

于 2015-03-02T03:04:56.177 回答