PHP Substring Function

I do a lot of work with data and strings, and one of the features lacking in the PHP (and most other) languages, is the ability to grab a portion of text from a string between two words.

For instance, if you wanted to grab the person's name from the string "My name is Adam", it takes a bit of doing.

In 2006 when I was writing my dissertation, I added two functions - substring and (a case insensitive version) subistring.

They take an input string, and optional start and end strings, and will find the text between them.

if (!function_exists('substring')) {
 function substring($document,$start='',$end='') {

        if ($start) {
            $start_position = strpos($document,$start);
            if (!($start_position === false)) $start_position = $start_position+strlen($start);
            }
        else $start_position = 0;

        if ($end) $end_position = @strpos($document,$end, $start_position);
        else { $end_position = strlen($document);}

        if ($start_position === false || $end_position === false) return "";

        return trim(substr($document,$start_position,$end_position-$start_position));

    }
}
if (!function_exists('subistring')) {
 function subistring($document,$start='',$end='') {

        if ($start) {
            $start_position = stripos($document,$start);
            if (!($start_position === false)) $start_position = $start_position+strlen($start);
            }
        else $start_position = 0;

        if ($end) $end_position = @stripos($document,$end, $start_position);
        else { $end_position = strlen($document);}

        if ($start_position === false || $end_position === false) return "";

        return trim(substr($document,$start_position,$end_position-$start_position));

    }
}

You can therefore use these functions as follows:

substring("Hello my name is Adam", "name is", "") => "Adam"
substring("This is the <h1>Title</h1>", "<h1>", </h1>") => "Title"
substring("Here you can't find the string, "Hello", "end") => ""
subistring("This is a Case-Insensitive substring", "case-", "substring") => "Insensitive"



Want to get in touch?