# 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.

-

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);

-
The second one also caches double backslash as a replacement and from Test \\ Blah I get Test <div>\\</div> Blah. Also I'm using PHP equivalents /(\$.*?\$)/, "<span>$1</span>" and /(\\$.*?\\$)/, "<div>$1</div>". –  svenkapudija Jun 25 '12 at 9:34
@svenkapudija: I'm not following. You're using those in JavaScript, right? The second one shouldn't be capturing "\\" because the $ is mandatory. – Tim Pietzcker Jun 25 '12 at 9:37 PHP actually, my fault, now I added the tag to the question. I removed the javascript escapes and it doesn't mark double backslash but neither the \[$ signs - /($.*?$)/ –  svenkapudija Jun 25 '12 at 9:46
@svenkapudija: OK, in that case you need to change the regex because PHP needs four backslashes in a regex to match a single literal backslash. (And use \0 instead of \$&.) See my edit. –  Tim Pietzcker Jun 25 '12 at 9:53
Got it! Also needed /s modifier at the end for multiple lines (overlooked that one). Thanks. –  svenkapudija Jun 25 '12 at 9:57