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

Roy*_*sen 19 php string

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

$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]})
Run Code Online (Sandbox Code Playgroud)

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

MLe*_*vre 44

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

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

echo $last_word;
Run Code Online (Sandbox Code Playgroud)

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

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

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.
Run Code Online (Sandbox Code Playgroud)

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

  • @Sebastian上下文很重要,但是在1000字的情况下,是的,我可能仍然愿意.除非您运行脚本数千次/数百万次,否则与此方式相比,以另一种方式保存的时间不会超过我写这篇评论所花费的时间. (2认同)
  • 对于我们这些一次检查一个小字符串的人来说,这是非常合适的.谢谢. (2认同)

小智 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);
Run Code Online (Sandbox Code Playgroud)

  • 你这里不需要`$ last_word_end`.当省略`substr`的​​第三个参数时,该函数将从`$ last_word_start`到字符串结尾.如果你坚持拥有它,那么它应该是`$ last_word_end = strlen($ str) - $ last_word_start`(你的通常不会给出错误的结果,但它没有意义;如果字符串不包含空格,那将是错误的). (4认同)

ran*_*uwe 6

这取决于您尝试执行的操作(从您的描述中很难理解),但要从字符串中获取最后一个单词,您可以执行以下操作:

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

echo $split[count($split)-1];
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅如何获取字符串的最后一个单词。