Skip to content
PHP Logo

What alternative methods can be used to split a string based on the last occurrence of a specific character in PHP?

When splitting a string based on the last occurrence of a specific character in PHP, one approach is to use the `strrpos()` function to find the position of the last occurrence of the character, and then use `substr()` to split the string accordingly.

php
$string = "Hello World, PHP is awesome";
$delimiter = ',';
$lastOccurrence = strrpos($string, $delimiter);

if ($lastOccurrence !== false) {
    $firstPart = substr($string, 0, $lastOccurrence);
    $secondPart = substr($string, $lastOccurrence + 1);
    
    echo $firstPart . "\n";
    echo $secondPart;
} else {
    echo "Delimiter not found in string.";
}