Built From Developers For Developers
» Kuikie.com » Snippets » PHP » Strings » PHP. Retrieve the Part of the String Left From Specified Substring
  Categories
  PHP
    Arrays
    Date & Time
    Files & Directories
    Globalization
    Images
    OOP
    Other
    Strings
    User Interface
 

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;
}
 
©2012 Sinevia Ltd Terms of Use         Privacy Policy Valid XHTML 1.0 Transitional