$re = '/
(?<firstcapture> ~Start [^~]* ) #_(3)
(?<randomStuff> .*? ) #_(4)
(?<loop_first> #_(5 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (1)
) #_(5 end)
(?:
(?<loop_middle> #_(6 start)
(?:
(?:
~
(?: LOOP )
\d [^~]
)
.*?
)*
) #_(6 end)
(?<loop_last> #_(7 start)
(?:
~
(?: LOOP )
\d [^~]
)
( .*? ) # (2)
) #_(7 end)
)?
(?<end> ~End [ ] stuff~ ) #_(8)
/mx';
$str = ' BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP2 hello2~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~LOOP3 hello3~End stuff~
BlahBlahBlah~Start capture~Yadda~Yadda~Yadda~LOOP1 hello1~End stuff~
';
$subst = "${firstcapture}${randomStuff}${loop_last}${loop_middle}${loop_first}${end}";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php