grabbing the last word in a sentence
Moderator: General Moderators
grabbing the last word in a sentence
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) {
?
?
?
}
ex.
$someString = 'my name is john';
$lastWord = some_function ($someString);
some_function ($variable) {
?
?
?
}
Re: grabbing the last word in a sentence
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];
}
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
Code: Select all
function lastWord($sentence)
{
return array_pop(explode(' ', $sentence));
}Code: Select all
$sentence = 'gimme da last word of this here string';
echo lastWord($sentence);Code: Select all
stringSet Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Re: grabbing the last word in a sentence
Code: Select all
strrchr($string, ' ');Re: grabbing the last word in a sentence
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
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
That fails if the string is only 1 word long, eg there's no spaces.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, ' '));
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
This looks like it should work:
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.
Code: Select all
$target = 'Can I have the last word please?';
$pattern = "/.* ([\w-']*).*/";
preg_match($pattern,$target,$matches);
echo $matches[1];Real programmers don't comment their code. If it was hard to write, it should be hard to understand.