How to obtain the last word of a string

后端 未结 8 2219
囚心锁ツ
囚心锁ツ 2020-12-03 19:53

we have that string:

\"I like to eat apple\"

How can I obtain the result \"apple\" ?

相关标签:
8条回答
  • 2020-12-03 20:48

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

    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);
    
    0 讨论(0)
  • 2020-12-03 20:53

    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

    0 讨论(0)
提交回复
热议问题