How can substr() and strrpos() be used to extract a string until the last occurrence of a specific character in PHP?

To extract a string until the last occurrence of a specific character in PHP, you can use the strrpos() function to find the position of the last occurrence of the character, and then use substr() to extract the substring up to that position.

$string = "Hello, World! This is a sample string.";
$char = '!';

$lastOccurrence = strrpos($string, $char);
$extractedString = substr($string, 0, $lastOccurrence + 1);

echo $extractedString; // Output: Hello, World!