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

问题描述 投票:17回答:4

我已经尝试了一些事情来完成最后一部分我做了这个:

$string = 'Sim-only 500 | Internet 2500';
preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$string
AND
preg_match("/[^ ]*$/","",{abo_type[1]})

第一个不起作用,第二个返回一个数组,但真正需要字符串。

php string
4个回答
39
投票

如果你在句子的最后一个单词之后,为什么不做这样的事呢?

$string = '​Sim-only 500 ​| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);

echo $last_word;

我不建议使用正则表达式,因为它是不必要的,除非你真的想要出于某种原因。

$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.

他们提供的substr()方法可能更好

$string = 'Retrieving the last word of a string using PHP.';
$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start); // $last_word = PHP.

它更快,虽然它确实没有在这样的事情上产生那么大的差异。如果您经常需要知道100,000字符串的最后一个字,那么您应该以不同的方式处理它。


8
投票

这应该适合你:

$str = "fetch the last word from me";
$last_word_start = strrpos ( $str , " ") + 1;
$last_word_end = strlen($str) - 1;
$last_word = substr($str, $last_word_start, $last_word_end);

4
投票

这取决于你尝试做什么(从你的描述中很难理解)但是要从字符串中获取最后一个单词,你可以做到:

$split = explode(" ", $string);

echo $split[count($split)-1];

有关更多信息,请参阅How to obtain the last word of a string


1
投票

你去一个通用函数来从字符串中获取最后一个单词

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;
}
$string = '​Sim-​only 500 | Internet 2500​';
echo get_last_words(1,  $string );
© www.soinside.com 2019 - 2024. All rights reserved.