简体   繁体   English

如何获取两个标签之间的所有文本,包括 php 标签

[英]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.我想在 $str 中找到'<div class="brown">'</div>之间的所有内容,但我也想要标签。

I want obtain this in one var $find = '<div class="brown">This content brown</div>';我想在一个 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:

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.但是这个function没有获取标签,我也想要标签。

Thanks.谢谢。

I've rewritten your get_string_betwen method.我已经重写了您的get_string_betwen方法。 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_replace

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM