Snippet. PHP. Retrieve the Part of the String Right From Specified Substring

This PHP snippet shows how to find the first occurrence of a substring in string and returns the part of the string starting from the end of the found substring to the end of the string. The functionality is wrapped in a function, which can easily be reused i.e. in scraping a large amount of text.

//======================== START OF FUNCTION ==========================//
// FUNCTION: str_right_from                                            //
//=====================================================================//
function str_right_from($string,$match){
    $pos = strpos($string, $match);
    if ($pos === false) return false;
    return substr($string, $pos);
}
//=====================================================================//
//  FUNCTION: str_right_from                                           //
//========================== END OF METHOD ============================//

Example

$string = "My name is Alexander";

$name = str_right_from($string,"My name is ");

if ($name !== false) {
    echo "The following name was found: ".$name;
}

Updated on: 16 Apr 2024