- preg_replace_callback: documentation ( source)
<?php
$content= <<<'DATA'
## Section title
Lorem ipsum *dolores* sic amet. $E = mc^2$, and since :
$$
\cos(3*\pi*\sqrt{2}) = \delta
$$
DATA;
$content = preg_replace_callback(
'/^\$+(?:\R(?!\$+$).*)*\R\$+$(*SKIP)(*FAIL)|([*_])((?:(?!\1).)+)\1/m',
function ($m) {
return "<i>" . $m[2] . "</i>";
},
$content
);
echo $content;