<?
$haystack = '%[hello there %[something in here] something more in here] then more text %[and finally] and then some more text that should not be included';
$startneedle = "%[";
$stopneedle = "]";
$pos = -1;
$i=0;
while (($pos=strpos($haystack,$startneedle,$pos+1))!==false) $start_array[$i++]=$pos;
$pos = -1;
$i=0;
while (($pos=strpos($haystack,$stopneedle,$pos+1))!==false) $stop_array[$i++]=$pos;
$pair= array();
//now match start and stops
$start=0;
foreach ($stop_array as $stop):
$test = false;
$prev_key = "";
$prev_val = "";
foreach ($start_array as $key=>$start):
$test = ($start > $stop) ? true : false;
if ($test != false):
$pair[] = array ("start"=>$prev_val, "stop" => $stop);
unset ($start_array[$prev_key]);
break;
else:
endif;
$prev_key = $key;
$prev_val = $start;
endforeach;
if ($test === false) {$pair[] = array ("start"=>$prev_val, "stop" => $stop);}
endforeach;
foreach ($pair as $p):
$len = $p['stop'] - $p['start'] - strlen($stopneedle) - 1;
$contents[] = substr ($haystack, $p['start'] + strlen($startneedle), $len);
endforeach;
echo "the input string was <br/><i>$haystack</i><br/>";
echo "<br/>nested tag contents are<br/><pre>";
print_r ($contents);
echo "</pre>";
?>