For the scenario where there are many occurrences, I usually use preg_split. When there is only one, then I use strpos. Something like this:
PHP Code:
<?php
$string = '<html>
<head>
<title>My page</title>
</head>
<body>
<h1>A page of content</h1>
<p>The paragraph of text on the page of content.</p>
</body>
</html>';
$start_tag_start = strpos($string,'<body'); //NOTE: The closing '>' has been left off in case of other tags being around
if ($start_tag_start !== false) {
//Calculate end of start tag
$start_tag_end = strpos($string,'>',$start_tag_start) + 1;
//Since we're searching for the end tag, start from the end and search backwards
$end_tag_start = strrpos($string,'</body>');
/*
* Alternatively, we could find the ending tag following the start tag with this
* Use the method which is likely to have to search through fewer characters
* to return the result.
*
* $end_tag_start = strpos($string,'</body>',$start_tag_end);
*/
if ($end_tag_start !== false && $end_tag_start > $start_tag_end) {
//trim() usage is optional
$desired_contents = trim(substr($string,$start_tag_end,$end_tag_start - $start_tag_end));
}
}
echo '<textarea rows="30" cols="80">'.$desired_contents.'</textarea><br /><br />';
//Now, to search using preg_split
$string = '<html>
<head>
<title>My page</title>
</head>
<body>
<h1>A page of content</h1>
<p>The paragraph of text on the page of content.</p>
<p>The second paragraph of text on the page of content.</p>
</body>
</html>';
$tag_name = 'p'; //ONLY LETTERS. Try $tag_name = 'body';
$tag_matches = preg_split('/<[\/]?'.$tag_name.'[^>]*?>/i',$string);
$desired_contents = '';
$match_count = count($tag_matches);
if ($match_count > 1) {
$shown_count = 0;
for ($index=1;$index < $match_count;$index += 2) {
$desired_contents .= ++$shown_count.") ".trim($tag_matches[$index])."\n\n";
}
}
echo '<textarea rows="30" cols="80">'.$desired_contents.'</textarea>';
?>