Search code examples
phpstringgetfind

How to get all text between two tags including php tags


I have this string:

$str = 'This is the content total <div class="brown">This content brown</div> and this another content <div class="red">This is content brown</div> and this finish.';

I want find in $str all between '<div class="brown">' and </div>, but I want too the tags.

I want obtain this in one var $find = '<div class="brown">This content brown</div>';

And then delete the obtained part of the initial text

$str = 'This is the content total and this another content <div class="red">This is content brown</div> and this finish.';

I have tried this function:

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);
    }

But this function not obtain tags, I want tags too.

Thanks.


Solution

  • I've rewritten your get_string_betwen method. And included the code I used to test it. Does this meet your requirements? And to get the other string, simply use str_replace as shown bellow.

    $str = 'This is the content total <div class="brown">This content brown</div> and this another content <div class="red">This is content brown</div> and this finish.';
    
    $result = get_string_between($str, "<div", "</div>");
    echo "<pre>" . htmlentities($result) . "</pre>";
    
    $cleanedString = str_replace($result, "", $str);
    echo "<pre>" . htmlentities($cleanedString) . "</pre>";
    
    function get_string_between($string, $start, $end) {
        $offset = strpos($string, $start);
        $len = strpos($string, $end) - $offset + strlen($end);
        return substr($string, $offset, $len);
    }