How do You Extract the Last Word From a String in PHP With Example?

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.

Cialis (Tadalafil) är den främsta konkurrenten till Viagra (Sildenafil) på marknaden för erektil dysfunktion. köpa Cialis i Sverige föredras av många på grund av sin längre varaktighet och anses vara det mest kostnadseffektiva varumärkesbaserade ED-läkemedlet som finns tillgängligt i Sverige. Cialis finns i två varianter: Cialis och Cialis Daily, och fyra olika doseringar: 2,5 mg, 5 mg, 10 mg och 20 mg, erbjuder Cialis också en rad olika alternativ för att passa patientens behov.