Page 1 of 1

grabbing the last word in a sentence

Posted: Sun Oct 26, 2008 8:30 pm
by abgoosht
I have a string with n number of words and I'm trying to take the last word. Do you have any suggestions, I can't seem to get it....

ex.
$someString = 'my name is john';
$lastWord = some_function ($someString);

some_function ($variable) {
?
?
?
}

Re: grabbing the last word in a sentence

Posted: Sun Oct 26, 2008 11:50 pm
by sirish
Each word in the sentence is separated by a space so the following function will work

function some_function($variable){
$variable="my name is john";
$tmpArr=explode(" ",$variable);
$last_index=count($tmpArr)-1;
return $tmpArr[$last_index];
}

Re: grabbing the last word in a sentence

Posted: Mon Oct 27, 2008 12:11 am
by s.dot

Code: Select all

function lastWord($sentence)
{
    return array_pop(explode(' ', $sentence));
}
Test:

Code: Select all

$sentence = 'gimme da last word of this here string';
echo lastWord($sentence);
Result:

Code: Select all

string

Re: grabbing the last word in a sentence

Posted: Mon Oct 27, 2008 12:25 am
by Jenk

Code: Select all

strrchr($string, ' ');
may want to trim $string.

Re: grabbing the last word in a sentence

Posted: Mon Oct 27, 2008 2:36 pm
by abgoosht
thanks a lot guys. i actually ended up using this

Code: Select all

 
        $str = 'here is some string and we want the last word';
        $str = trim($str);
        $temp=explode(" ", $str);
        echo $temp[count($temp)-1];
 

Re: grabbing the last word in a sentence

Posted: Tue Oct 28, 2008 4:19 pm
by André D
That works fine, but I would prefer strrchr(), like Jenk suggested. It requires less code and is more efficient.

Code: Select all

$str = 'here is some string and we want the last word';
echo trim(strrchr($str, ' '));

Re: grabbing the last word in a sentence

Posted: Tue Oct 28, 2008 5:40 pm
by onion2k
André D wrote:That works fine, but I would prefer strrchr(), like Jenk suggested. It requires less code and is more efficient.

Code: Select all

$str = 'here is some string and we want the last word';
echo trim(strrchr($str, ' '));
That fails if the string is only 1 word long, eg there's no spaces.

All the solutions posted so far fail if there's punctuation in the string ... eg "What is the last word?" will return "word?".

Re: grabbing the last word in a sentence

Posted: Tue Oct 28, 2008 6:02 pm
by pickle
This looks like it should work:

Code: Select all

$target = 'Can I have the last word please?';
$pattern = "/.* ([\w-']*).*/";
preg_match($pattern,$target,$matches);
echo $matches[1];
I could only think of a hyphen and apostrophe (though it's a single-quote there) as special characters that show up in words. Obviously the pattern can be updated.