A vast majority of answers here don't answer the edited part, I guess they were added before. It can be done with regex, as one answer mentions. I had a different approach.
This function searches $string and finds the first string between $start and $end strings, starting at $offset position. It then updates the $offset position to point to the start of the result. If $includeDelimiters is true, it includes the delimiters in the result.
If the $start or $end string are not found, it returns null. It also returns null if $string, $start, or $end are an empty string.
function str_between(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
if ($string === '' || $start === '' || $end === '') return null;
$startLength = strlen($start);
$endLength = strlen($end);
$startPos = strpos($string, $start, $offset);
if ($startPos === false) return null;
$endPos = strpos($string, $end, $startPos + $startLength);
if ($endPos === false) return null;
$length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
if (!$length) return '';
$offset = $startPos + ($includeDelimiters ? 0 : $startLength);
$result = substr($string, $offset, $length);
return ($result !== false ? $result : null);
}
The following function finds all strings that are between two strings (no overlaps). It requires the previous function, and the arguments are the same. After execution, $offset points to the start of the last found result string.
function str_between_all(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
$strings = [];
$length = strlen($string);
while ($offset < $length)
{
$found = str_between($string, $start, $end, $includeDelimiters, $offset);
if ($found === null) break;
$strings[] = $found;
$offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
}
return $strings;
}
Examples:
str_between_all('foo 1 bar 2 foo 3 bar', 'foo', 'bar')
gives [' 1 ', ' 3 ']
.
str_between_all('foo 1 bar 2', 'foo', 'bar')
gives [' 1 ']
.
str_between_all('foo 1 foo 2 foo 3 foo', 'foo', 'foo')
gives [' 1 ', ' 3 ']
.
str_between_all('foo 1 bar', 'foo', 'foo')
gives []
.