/**
* Returns the last word from a given string.
*
* @param string $input The input string.
* @return string The last word, or an empty string if none found.
*/
function getLastWord(string $input): string {
// If the string is empty or contains only whitespace, return empty string
if (trim($input) === "") {
return "";
}
// Remove leading and trailing spaces
$input = trim($input);
// Find the last space in the string
$pos = strrpos($input, " ");
// If a space was found, return the substring after it; otherwise return the whole string
return $pos !== false ? substr($input, $pos + 1) : $input;
}
// Test cases
$tests = [
"vb.net javascript php c c++ python c#",
"",
"c#",
"c c++ java ",
" "
];
foreach ($tests as $index => $t) {
echo ($index + 1) . ". " . getLastWord($t) . PHP_EOL;
}
/*
run:
1. c#
2.
3. c#
4. java
5.
*/