1

我需要在一块文本中找到 2 个标签并保留它们之间的任何文本。

例如,如果“开始”标签是-----start-----,而“结束”标签是-----end-----

鉴于此文本:

rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
-----end-----gcgkhjkn

我只需要保留两个标签之间的文本:isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r

有任何想法吗?谢谢你。

4

3 回答 3

12

这里有几种方法:

$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]);
}
于 2012-06-30T21:02:39.923 回答
7

试试这个:

$start = '-----start-----';
$end   = '-----end-----';
$string = 'rtyfbytgyuibg-----start-----isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r-----end-----gcgkhjkn';
$output = strstr( substr( $string, strpos( $string, $start) + strlen( $start)), $end, true);
echo $output;

将打印

isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
于 2012-06-30T21:01:35.940 回答
0

如果您的字符串实际上是 HTML 数据,则必须添加htmlentities($lump)以便它不会返回空:

$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);
于 2017-05-18T18:59:40.280 回答