Simple: How to replace "all between" with php?

faq picture faq · Jul 29, 2011 · Viewed 42.9k times · Source
$string = "<tag>i dont know what is here</tag>"
$string = str_replace("???", "<tag></tag>", $string);
echo $string; // <tag></tag>

So what code am i looking for?

Answer

Felix Kling picture Felix Kling · Jul 29, 2011

A generic function:

function replace_between($str, $needle_start, $needle_end, $replacement) {
    $pos = strpos($str, $needle_start);
    $start = $pos === false ? 0 : $pos + strlen($needle_start);

    $pos = strpos($str, $needle_end, $start);
    $end = $pos === false ? strlen($str) : $pos;

    return substr_replace($str, $replacement, $start, $end - $start);
}

DEMO