You can extract the last word from a string in PHP using various methods. One common approach is to use the `strrpos()` function to find the position of the last space in the string, and then extract the substring starting from that position. Here’s an example:
<?php // Example string $string = "Hello world! This is an example."; // Find the position of the last space in the string $lastSpacePos = strrpos($string, ' '); // If a space is found, extract the last word if ($lastSpacePos !== false) { $lastWord = substr($string, $lastSpacePos + 1); } else { // If no space is found, the entire string is the last word $lastWord = $string; } // Output the last word echo "Last word: " . $lastWord; ?>
In this example:
1. We have the string “Hello world! This is an example.”
2. We use `strrpos()` to find the position of the last space in the string.
3. If a space is found, we extract the substring starting from the position of the last space plus 1 (to exclude the space itself).
4. If no space is found (i.e., the string contains only one word or is empty), we consider the entire string as the last word.
5. Finally, we output the last word.
Output:
Last word: example.
This extracts the last word from the given string.