简体   繁体   中英

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

explode() is good, but once you've done that you can use

$size = sizeof($statusMessage);

and last 3 are

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

this catches 1 to 3 words and if the row is only 3 long, other regex one was close

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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