hamburger hamburger - 1 month ago 12
PHP Question

How to get the last words in a string with preg_match

I'am trying to get the last few words in a string.
For the last word I'am using this:

$string = "Hallo dies ist ein extrem langer Text den ich gern gekuerz haette, leider bin ich selbst zu doof dafür und mach hier einen test.";

$pattern = '/[^ ]*$/';

preg_match($pattern, $string, $result);

echo "<br>The last word is:------ ". $result[0] ." ---------<br>";


it works fine. But I do not get in to run with for ex. the last tree words.
I do not know how to change the pattern.
Thanks for any help in advance.

Answer

That will do the job

$pattern = '/(([^ ]*)\s+([^ ]*)\s+([^ ]*))$/';

Example

or

$pattern = '/((([^ ]*)[\s.]+){3})$/';

Example