简体   繁体   English

从字符串中获取最后三个单词?

[英]Get last 3 words from the string?

How do you get last 3 words from the string?你如何从字符串中获取最后三个单词?

I managed to get working doing like this:我设法像这样开始工作:

$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;

Is there a shorter way?有没有更短的方法? Maybe there is a PHP function that I did not know..也许有一个我不知道的 PHP function..

explode() is good, but once you've done that you can use explode() 很好,但是一旦你完成了,你就可以使用

$size = sizeof($statusMessage);

and last 3 are最后3个是

$statusmessage[$size-1]; 
$statusmessage[$size-2]; 
$statusmessage[$size-3]; 
preg_match('#(?:\s\w+){3}$#', $statusMessage );

preg_match("/(?:\w+\s*){1,3}$/", $input_line, $output_array); preg_match("/(?:\w+\s*){1,3}$/", $input_line, $output_array);

this catches 1 to 3 words and if the row is only 3 long, other regex one was close这会捕获 1 到 3 个单词,如果该行只有 3 个长,则其他正则表达式很接近

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM