Skip to content
PHP Logo

What alternative function could be used instead of strrchr to achieve the desired result?

The issue with using strrchr is that it only returns the last occurrence of a character in a string, whereas we want to find the first occurrence. To achieve the desired result, we can use the strpos function to find the position of the first occurrence of a character in a string. We can then use substr to extract the substring from the beginning of the original string up to the position of the character.

php
$string = "Hello, World!";
$char = ',';
$position = strpos($string, $char);

if ($position !== false) {
    $substring = substr($string, 0, $position);
    echo $substring;
} else {
    echo "Character not found in string.";
}