Как извлечь текст между 2 тегами в php

Мне нужно найти 2 тега в куске текста и сохранить любой текст между ними.

Например, если тегом «Начало» было -----start----- а тегом «End» было -----end-----

С учетом этого текста:

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

Мне нужно сохранить только текст между двумя тегами: isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r

Есть идеи? Спасибо.

Solutions Collecting From Web of "Как извлечь текст между 2 тегами в php"

Вот несколько способов:

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

Попробуй это:

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

Это напечатает :

 isnv4b987b6vdc5y6ughnjmn9b8v76ctyubinn98b76r 

Если ваша строка является фактически данными 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);