How can I extract the substring located between two specific strings in PHP?

Solution: 1

If you need to extract text between two different delimiters (e.g., [foo] and [/foo]), you can use a helper function like this (credit: Justin Cook):


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 usage:


$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');

echo $parsed; // Output: dog

Solution: 2

A simple way to extract text between two markers is with a regular expression:


$str = 'before-str-after';

if (preg_match('/before-(.*?)-after/', $str, $match) === 1) {
    echo $match[1]; // Output: str
}

Here, (.*?) captures the content between before- and -after.