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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11029447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:36:48  来源:igfitidea点击:

How to obtain the last word of a string

php

提问by Oscar

we have that string:

我们有那个字符串:

"I like to eat apple"

How can I obtain the result "apple"?

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

回答by Rick Kuipers

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

回答by user2029890

a bit late to the party but this works too

参加聚会有点晚,但这也有效

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

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

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

回答by m4rtijn

Try:

尝试:

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

回答by flowfree

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

回答by Milan Halada

Try this:

尝试这个:

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

回答by M Khalid Junaid

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);

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

回答by Talha Mughal

<?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.

输出将为apple.

回答by Reena Mori

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

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