首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中提取两个标签之间的文本

如何在php中提取两个标签之间的文本
EN

Stack Overflow用户
提问于 2012-07-01 04:58:51
回答 3查看 10.2K关注 0票数 1

我需要在一个文本块中定位2个标签,并保持它们之间的任何文本。

例如,如果"Begin“标记是-----start-----,而"End”标记是-----end-----

给定此文本:

代码语言:javascript
复制
rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
-----end-----gcgkhjkn

我只需要将文本放在两个标记之间:isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r

有什么想法吗?谢谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-07-01 05:02:40

以下是几种方法:

代码语言:javascript
复制
$lump = 'rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r-----end-----gcgkhjkn';
$start_tag = '-----start-----';
$end_tag = '-----end-----';

// method 1
if (preg_match('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
    echo $matches[1];
}

// method 2 (faster)
$startpos = strpos($lump, $start_tag) + strlen($start_tag);
if ($startpos !== false) {
    $endpos = strpos($lump, $end_tag, $startpos);
    if ($endpos !== false) {
        echo substr($lump, $startpos, $endpos - $startpos);
    }
}

// method 3 (if you need to find multiple occurrences)
if (preg_match_all('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
    print_r($matches[1]);
}
票数 12
EN

Stack Overflow用户

发布于 2012-07-01 05:01:36

试试这个:

代码语言:javascript
复制
$start = '-----start-----';
$end   = '-----end-----';
$string = 'rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r-----end-----gcgkhjkn';
$output = strstr( substr( $string, strpos( $string, $start) + strlen( $start)), $end, true);
echo $output;

will print

代码语言:javascript
复制
isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
票数 7
EN

Stack Overflow用户

发布于 2017-05-19 02:59:40

如果你的字符串实际上是超文本标记语言数据,你必须添加htmlentities($lump),这样它就不会返回空:

代码语言:javascript
复制
$lump = '<html><head></head><body>rtyfbytgyuibg-----start-----<div>isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r</div>-----end-----gcgkhjkn</body></html>';
$lump = htmlentities($lump) //<-- HERE
$start_tag = '-----start-----';
$end_tag = '-----end-----';

// method 1
if (preg_match('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
        echo $matches[1];
}

// method 2 (faster)
$startpos = strpos($lump, $start_tag) + strlen($start_tag);
if ($startpos !== false) {
   $endpos = strpos($lump, $end_tag, $startpos);
        if ($endpos !== false) {
            echo substr($lump, $startpos, $endpos - $startpos);
        }
}

// method 3 (if you need to find multiple occurrences)
if (preg_match_all('/'.preg_quote($start_tag).'(.*?)'.preg_quote($end_tag).'/s', $lump, $matches)) {
        print_r($matches[1]);
 }

// method 4 
$output = strstr( substr( $string, strpos( $string, $start) + strlen( $start)), $end, true);

//Turn back to regular HTML
echo htmlspecialchars_decode($output);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11277620

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档