How can the PHP function TRIM and SUBSTRING_INDEX be combined to remove characters after the last space in a string?

To remove characters after the last space in a string, you can first use the SUBSTRING_INDEX function to extract the substring before the last space, and then use the TRIM function to remove any trailing spaces. This combination allows you to effectively trim the string after the last space.

$string = "This is a sample string with extra characters after the last space";
$trimmedString = rtrim(substr($string, 0, strrpos($string, ' ')));
echo $trimmedString;