$re = '/(?:^|\n)##\s[^\n]*\n+(.*?)(?=\n##?\s|$)/s';
$str = '# This is an H1
content
content
content
## This is an H2 that ends in another H2
matched content 1
matched content 1
matched content 1
## This is an H2 that ends in an H1
matched content 2
matched content 2
matched content 2
# This is an H1, it\'s content doesn\'t belong to any H2
content
content
content
## This is an H2 that goes on until the end of the file
matched content 3
matched content 3
### This H3 belongs to the H2 above
matched content 4
matched content 4';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
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