How to Get the Last Word from String in PHP?

To get the last word from a string in PHP, you can use a combination of string manipulation functions. One common approach is to split the string into an array of words and then extract the last element of the array. Here’s how you can do it:

function getLastWord($str) {
    // Remove any leading/trailing white spaces to ensure accurate results
    $trimmedStr = trim($str);

    // Split the string into an array of words
    $wordsArray = explode(' ', $trimmedStr);

    // Get the last element (last word) from the array
    $lastWord = end($wordsArray);

    return $lastWord;

// Example usage:
$originalString = "This is a sample string";
$lastWord = getLastWord($originalString);
echo $lastWord; // Output: "string"



In this example, the getLastWord() the function takes the input string and removes any leading or trailing white spaces using trim(), then splits the string into an array of words using explode() with a space delimiter. Finally, it fetches the last element of the array (which is the last word) using end() and returns it.

Keep in mind that this approach assumes that words in the string are separated by spaces. If your use case involves different delimiters or more complex word separation rules, you may need to adjust the code accordingly.