How to extract text between 2 tags in php

前端 未结 3 367
温柔的废话
温柔的废话 2021-01-07 11:12

I need to locate 2 tags in a lump of text and keep whatever text is between them.

For example if the \"Begin\" tag was -----start----- and the \"End\" t

相关标签:
3条回答
  • 2021-01-07 11:55

    Here are a couple of ways:

    $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]);
    }
    
    0 讨论(0)
  • 2021-01-07 12:05

    Try this:

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

    This will print:

    isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r
    
    0 讨论(0)
  • 2021-01-07 12:13

    If your string is actually HTML data, you have to add htmlentities($lump) so it won't return empty:

    $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 讨论(0)
提交回复
热议问题