you can try this using preg_replace_callback:
//if html is retrieved in a variable like $html, then
$html = "<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>
<div class='first'>first</div>
<div class='second'>second</div>";
$validate = array('first'=>true,'second'=>true);
$response = trim(preg_replace_callback('/<div\s?.*\/div>/',function($match)use(&$validate){
reset($validate);$key = key($validate);
if(strstr($match[0],$key) != false && $validate[$key] == true){
$validate[$key] = false;
return $match[0];
}
next($validate);$key = key($validate);
if(strstr($match[0],$key) != false && $validate[$key] == true){
$validate[$key] = false;
return $match[0];
}
},$html));
var_dump($response);