Snippet. PHP. Retrieve the Part of the String Left 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 beginning to the position of the found substring. The functionality is wrapped in a function, which can easily be reused i.e. in scraping a large text.

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

Example

$string = "Alexander is my name!";

$name = str_left_from($string," is my name");

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

Updated on: 29 Mar 2024