$from = 0;
while()$begin = strpos('a1' , $string ,$from))!==false)
{
$last = strpos('a2' , $string , $from + strlen('a1'));
$middle = strpos('a3' , $string , $from + strlen('a1'));
if($middle < $last)
{
$from+=strlen('a1');
continue;
}
echo substr($string , $from , $last - $from);
$from = $last+strlen('a2');
}