How to extract the part of a string before the last occurrence of a specific character in PHP?

Solution 1:


$string = "Hello World Again";
echo substr($string, 0, strrpos($string, ' ')); // Outputs: Hello World

This extracts everything up to the last space.
If no space is found, the function won’t output anything.

Solution 2:

A straightforward approach is to split the string into words, remove the last one, and then join the rest back together:


$string = "Hello World Again";
$parts = explode(' ', $string);
array_pop($parts);
$result = implode(' ', $parts);

echo $result; // Outputs: Hello World