PHP: Return a string between two strings or tags.

Posted November 9th, 2012

Returns the contents of a string between two unique strings. Useful for returning the portion of a string found between the two supplied strings.

// String to extract string from.
$string = 'This is a string to extract <tag>contents between tags</tag> from.';

// Call the function.
// Value Echoed: contents between tags
echo extractString($string, '<tag>', '</tag>');

// Function that returns the string between two strings.
function extractString($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);