$re = '/(?:\n+|\A)?
(?<code_all>
(?<code_start>
[ ]{0,3}
(?:
(?<with_backtick>[`]{3,})
|
(?<with_tilde>[~]{3,})
)
)
[ \t]*
(?(<with_tilde>)
(?:
(?:
(?:
(?<code_class>(?&_code_class))
(?:
[ \t]*
\{[[:blank:]\h]*(?<code_attr>(?&_code_attr))[[:blank:]\h]*\}
)?
)
|
(?:
\{[[:blank:]\h]*(?<code_attr>(?&_code_attr))[[:blank:]\h]*\}
)
)?
)
|
(?:
(?:
(?<code_class>(?&_code_class))
(?:
[ \t]*
\{[[:blank:]\h]*(?<code_attr>(?&_code_attr))[[:blank:]\h]*\}
)?
)
|
(?:
\{[[:blank:]\h]*(?<code_attr>(?&_code_attr))[[:blank:]\h]*\}
)
)
)
\n+
(?<code_content>.*?)
\n+
(?<!`)
\g{code_start}
(?!`)
[ \t]*
(?:\n|\Z)
)
(?<code_trailing_new_line>\n|\Z)
(?(DEFINE)
(?<_code_class> [\w\-\.]+)
(?<_code_attr> [^\}]+)
)/mJsx';
$str = '``` .html
<ul>
<li>Code block first in file</li>
<li>doesn\'t work under some circumstances</li>
</ul>
```
`````` .html {#codeid}
</div>
``````
~~~ .html
<ul>
<li>Code block first in file</li>
<li>doesn\'t work under some circumstances</li>
</ul>
~~~
~~~
<div>
~~~
~~~
<div>
~~~
~~~
<div>~~~</div>
~~~
~~~
<p>```
```
<p>```
~~~
~~~
Some text
Indented code block sample code
~~~
~~~~
In code block
~~~
Still in code block
~~~~~
Still in code block
~~~~
~~~~~ .html {#codeid}
</div>
~~~~~
';
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