Search code examples
phpregexmarkdownmathjax

Regex replace pair of dollar signs


I have combined MathJax and Markdown markup and therefore I need to replace all $$ with <span>$$</span> so that Markdown don't render $$_^... signs from MathJax. Also all \[ \] must be replaced with <div>\[ \]</div>.

I found similar question but it's not exactly what I need. I need to convert this

This is $some$ math \[equation\] which I $like$.

to this

This is <span>$some$</span> math <div>\[equation\]</div> which I <span>$like$</span>.

Probably what I need to to is just in regex

text = text.replace(/\$.*?\$/g, "meow");

somehow include and $$ signs (or \[ \]) and just with $1 embed the text inside <span>$$1$</span> and adapt to PHP.


Solution

  • You need to do it in two steps because the replacement texts are different.

    First, replace the $..$:

    $text = preg_replace('/\$.*?\$/', '<span>\0</span>', $text);
    

    Then, replace the \[...\]:

    $text = preg_replace('/\\\\\[.*?\\\\\]/', '<div>\0</div>', $text);