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

35

我尝试了几种方法来获取最后一部分,我做了这个:

$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]})

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


请问您能具体说明您需要什么吗?只需要字符串的最后一个单词吗?在这种情况下是2500吗? - ranieuwe
是的,我想要2500,而且无论如何我都想要最后一个字。 - Roy van Wensen
2
可能是重复的问题:如何使用PHP获取句子中的最后一个字符串? - Benoît
你可能会发现array_pop(s($str)->words())很有用,这在这个独立库中可以找到。 - caw
10个回答

74
如果你想要获取句子中的最后一个单词,为什么不直接这样做呢?
$string = '​Sim-only 500 ​| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);

echo $last_word;

我不建议使用正则表达式,除非你有特别的原因需要使用。

在IT技术方面,这并非必要。

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

虽然这样做速度更快,但对于像这样的事情,它并没有太大的区别。如果您经常需要知道一个10万字字符串中的最后一个单词,那么您可能应该采用不同的方法。


1
那么,你会从一个1000个单词的句子中创建一个长度为1000的数组,只是为了获取最后一个单词吗? - Sebastian
2
@Sebastian 上下文很重要,但是在处理1000个单词的情况下,我可能仍然会这样做。除非您要运行脚本数千万次,否则用另一种方式节省的时间与我写这个评论所花费的时间相比,并不会更多。 - SubjectCurio
你的最后一个例子在字符串中只有一个单词时会漏掉第一个字母。修正后的代码是:$last_word = substr($string, strrpos(' ' . $string, ' ')); - Chris Jenks

9
这应该适用于您:
$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);

5
在这里你不需要使用$last_word_end。当substr函数的第三个参数被省略时,它会取出从$last_word_start到字符串结尾的所有字符。如果您坚持需要使用它,则应该是 $last_word_end = strlen($str) - $last_word_start(您通常不会得到错误结果,但它没有意义;如果字符串中不包含空格,则结果将是错误的)。 - Vedran Šego

6

根据你所尝试的操作(从你的描述中很难理解),但如果你要从字符串获取最后一个单词,你可以这样做:

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

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

详见如何使用PHP获取字符串的最后一个单词,了解更多信息。


3
现有的解决方案都可以正常工作,但我想要一个一行代码的解决方法。explode()可以将一个句子分成单词,但是直接将其传递给array_pop()end()会出现“只能传递变量”的提示。这时就需要用到array_slice()了。
$string = 'Sim-only 500 | Internet 2500';
echo array_slice(explode(' ', $string), -1)[0];

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

1
如果您想使用标签包装最后一个单词:
<?php
/**
 * Wrap last word with span
 * @author: Elron
 * https://dev59.com/nGMl5IYBdhLWcg3wMUeP
 */
function wrap_last_word($string) {
    // Breaks string to pieces
    $pieces = explode(" ", $string);

    // Modifies the last word
    $pieces[count($pieces)-1] = '<span class="is-last-word">' . $pieces[count($pieces)-1] . '</span>';

    // Returns the glued pieces
    return implode(" ", $pieces);
}

wrap_last_word('hello this is wrapped');
// returns this:
// hello this is <span class="is-last-word">wrapped</span>

1

这里有另一种从字符串中获取最后一个单词的方法

$my_string = "fetch the last word from me";
 
// Explode the string into an array
$my_string = explode(" ", $my_string);

// target the last word with end() function 
$my_string = end($my_string);

echo $my_string;

结果


0

有一个一行代码的解决方案。

basename(str_replace(' ', '/', 'hello world'));

将返回world


0

使用正则表达式的一行解决方案:

preg_replace('/.*\s/', '', $string);

这个正则表达式可以匹配所有以空格结尾的内容,由于正则表达式总是“尽可能地”匹配,因此它将匹配除了最后一个单词之外的所有内容。这也有一个优点,就是可以与任何“空格”字符(制表符、换行符等)一起使用。

但是最佳的性能/资源消耗解决方案是(如果只有一个单词,则无法工作):

substr($string, strrpos($string, ' ') + 1);

如果 $string 只包含一个单词,则此代码可能无法正常工作。 - Appoodeh
你的第二个选项确实是正确的。 - Clément Moulin - SimpleRezo
你的第二个选择确实是正确的。 - undefined

-1

只需使用此函数

function last_word($string)
{
    $pieces = explode(' ', $string);
    return array_pop($pieces);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接