PHP + Regular Expression to find the last word in string

18 10 2011

Below is the code to find the last word of a string

$pattern = '/[^ ]*$/';
$str = 'Hello world';
preg_match($pattern, $str, $results);

The $results[0] contains last word “world”. If we need to remove or replace the last word use below code.

preg_replace($pattern, '', $str);

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: