hamburger hamburger - 1 year ago 145
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 Source

That will do the job

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



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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download