Get String Between Strings

This function gets the substring located between the two strings passed as parameters, $start and $end. The $start and $end strings are not included in the returned string.

function get_string_between($string, $start, $end) {
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

Example:

PHP
$string = "This is the string and, the only string being passed in. I only want to remove some of it.";
$start = ', ';
$end = '.';

$returnedString = get_string_between($string, $start, $end);

Returns the string:

$returnedString == ", the only string being passed in."

Use the returned string:

$newSentence = str_replace($returnedString, "", $string);

$newSentence = "This is the string and I only want to remove some of it."

 

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use