user622378
user622378

Reputation: 2336

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

Upvotes: 2

Views: 3796

Answers (3)

Rob22
Rob22

Reputation: 91

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

Upvotes: 0

Jacob Eggers
Jacob Eggers

Reputation: 9322

preg_match('#(?:\s\w+){3}$#', $statusMessage );

Upvotes: 1

Scott C Wilson
Scott C Wilson

Reputation: 20016

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

Upvotes: 5

Related Questions