我们有那个字符串:
"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];
$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
.