$re = '/(\${1,2})[^]*?[^\\\\]\1|[^\$]+/';
$str = 'some text outside $ \\$2+\\$ $ which includes $\\$$
Now some $${}$$ $\\{\\}$inline mathjax $2+2$
And in new lines
$$
2+2
$$
$
2+2\\\\
3+3\\\\
4+4\\\\
$
more inline $2+2\\$ \\$2+2$ $2+2$, $3+4$
separated $2+2$ by some text $ 2+2 $ again
double newlines
$2+2$
$2+2$
Dollar again $ \\$42 $
$$ \\$42 $$
$$
\\frac{4}{2}+
\\frac{4}{2}
$$
And some more tests:
\\> a) $\\dr{1}{2}+\\left(\\dr23-\\dr34\\right)$<<<
\\> b) $\\dr{1}{5}+\\left(\\dr23-\\dr12\\right)$<<<
\\> c) $\\dr{1}{2}+\\left(\\dr{3}{4}-\\dr32\\right)$<<<
\\> d) $\\left(\\dr{3}{10}-\\dr{5}{2}\\right)+\\dr7{20}$<<<
\\> e) $\\dr{2}{3}+\\left(\\dr{3}{2}-\\dr14\\right)$<<<
\\> f) $\\left(\\dr{14}{5}-\\dr7{10}\\right)+\\dr{11}{10}$.<<<
$$
a^{\\rr mn}=\\sq[n]{a^m}.
$$
$$
\\begin{align}
&a^x\\cdot a^y=a^{x+y}\\\\
&\\dr{a^x}{a^y}=a^{x-y}\\\\
&(a^x)^y=a^{xy}\\\\
&(ab)^x=a^xb^x\\\\
&\\left(\\dr ab\\right)^x=\\dr{a^x}{b^x}.
\\end{align}
$$
$$
\\sq[4]{5\\sq5}=(5\\sq5)^{\\rr14}=(5\\.5^{\\rr12})^{\\rr14}=
(5^{1+\\rr12})^{\\rr14}=(5^{\\rr32})^{\\rr14}=5^{\\rr38}.
$$
Hope that\'s it.
';
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